【问题标题】:JQuery: Hide anchor if href is emptyJQuery:如果href为空,则隐藏锚点
【发布时间】:2011-11-27 00:28:21
【问题描述】:

这个已经有一段时间了。基本上,我需要检查.pdf-download 类的锚标记上的href 是空的,如果是,隐藏它。

我尝试了几个选项,但没有运气。这是我到目前为止所拥有的:

$("a.pdf-download").each(function (i) {
  if ($('[href]:empty',this).length == 1) { 
    $(this).hide();
  } else {
    $(this).show();
  }
});

【问题讨论】:

  • 嗨,伙计 - 我看到你已经问了三个问题并得到了一些很好的答案。勾选最佳答案旁边的复选标记,确保将答案标记为正确。这就是 SO 社区的工作方式。您可能还想阅读常见问题解答 - stackoverflow.com/faq

标签: jquery hide show-hide


【解决方案1】:
if ($(this).attr('href') != '') { 
    $(this).hide();
} else {
    $(this).show();
}

请注意,您也可以在 css 中使用 attribute selectors 执行此操作:

a.pdf-download[href='']{
    display:none;
}

这在 ie6 中不受支持。

【讨论】:

  • +1 - 我喜欢 CSS 解决方案。如果您愿意,也可以在 jQuery 中使用相同的选择器。 $('a[href=""]').hide();
  • 请注意,jQuery 选择器根本不会隐藏没有 href 属性的链接标签。
【解决方案2】:

您也可以使用 jQuery 选择器执行此操作,如下所示:

// Hide any links with blank href or no href attribute
$('a.pdf-download[href=], a.pdf-download:not([href])').hide();

【讨论】:

    【解决方案3】:

    使用此解决方案。当未定义href 属性时,它也会产生所需的结果。如果您使用 CSS 选择器 (JQuery),则不会检测到不存在的 href 属性。

    $("a.pdf-download").each(function (i) {
        if (!this.href) { 
            $(this).hide();
        } else {
            $(this).show();
        }
    })
    

    没有必要使用 JQuery 方法来获取href 属性,因为this.href 具有同样的可读性、更快并且得到普遍支持。

    【讨论】:

      【解决方案4】:

      这样的东西有用吗?

      $("a.pdf-download").each(function (i) {
        if ($(this).attr('href').length == 0) { 
          $(this).hide();
        } else {
          $(this).show();
        }
      });
      

      【讨论】:

      • 如果在元素上设置了href,则此方法有效,但如果不是,则会引发错误。如果您尝试$('<a>test</a>').attr('href').length,它将返回“TypeError:无法读取未定义的属性'长度'”,因为.attr('href') 返回undefined。我想在大多数情况下,这种方法可以正常工作,但值得注意的是这个警告。
      【解决方案5】:
      $(function() {
      
          $('a').each(function() {
              (!$(this).attr('href')) ? $(this).hide() : $(this).show();
          });
      
      });
      

      全能演示:http://jsfiddle.net/each/j9DGw/

      【讨论】:

        【解决方案6】:
        $("a.pdf-download").each(function() {
            var href = $(this).attr("href");
            if(href == '') {
                $(this).remove();
            }
        });
        

        $("a.pdf-download[href='']").remove() 
        

        【讨论】:

          【解决方案7】:

          我自己是一个 jquery 初学者,但我会这样做:

          $("a.pdf-download").each(function (i) {
          
              var aHref = $(this).attr('href');
          
              if (aHref == '' || !aHref) {
          
                  $(this).hide();
          
              };
          
          });
          

          演示:http://jsfiddle.net/BZq9c/1/

          【讨论】:

            猜你喜欢
            • 2014-01-21
            • 2014-06-27
            • 1970-01-01
            • 2021-11-24
            • 1970-01-01
            • 2023-04-03
            • 2012-01-08
            • 2013-04-02
            • 2020-11-06
            相关资源
            最近更新 更多