【问题标题】:jQuery hasAttr checking to see if there is an attribute on an element [duplicate]jQuery hasAttr 检查元素上是否有属性[重复]
【发布时间】:2010-11-22 00:43:15
【问题描述】:

如何检查 jQuery 中的元素是否有属性?类似于hasClass,但使用attr

例如,

if ($(this).hasAttr("name")) {
    // ...
}

【问题讨论】:

  • quickie: if( $(this).is('[ATTRIBUTE_NAME]') ) { /* ... */ } BTW: 这不再是那个问题的重复,只是关于不同问题的类似问题,链接的重复现在称为“选择元素按属性"

标签: jquery


【解决方案1】:
var attr = $(this).attr('name');

// For some browsers, `attr` is undefined; for others,
// `attr` is false.  Check for both.
if (typeof attr !== 'undefined' && attr !== false) {
    // ...
}

【讨论】:

  • 这样做可能会更好: if( typeof( $(this).attr('name') ) != 'undefined' ) { // ... } 因为 undefined 可以实际上使用一个简单的重新定义: undefined = 1
  • @FuzzyDunlop,是的,但如果 attr"",那也会返回 false。它应该是true,因为空属性是有效属性。此外,没有必要使用 double-not,因为 if 无论如何都会将其转换为 bool。
【解决方案2】:

$(this).is("[name]") 怎么样?

[attr] 语法是具有 attr 属性的元素的 CSS 选择器,.is() 检查调用它的元素是否与给定的 CSS 选择器匹配。

【讨论】:

    【解决方案3】:

    如果您要经常检查属性是否存在,我建议您创建一个 hasAttr 函数,按照您在问题中的假设使用:

    $.fn.hasAttr = function(name) {  
       return this.attr(name) !== undefined;
    };
    
    $(document).ready(function() {
        if($('.edit').hasAttr('id')) {
            alert('true');
        } else {
            alert('false');
        }
    });
    
    <div class="edit" id="div_1">Test field</div>
    

    【讨论】:

      【解决方案4】:

      你离得太近了,这太疯狂了。

      if($(this).attr("name"))
      

      没有 hasAttr 但按名称点击属性只会返回 undefined 如果它不存在。

      这就是为什么下面的工作。如果您从 #heading 中删除 name 属性,则会触发第二个警报。

      更新:根据 cmets,如果属性存在,则以下内容有效那里是空的

      <script type="text/javascript">
      $(document).ready(function()
      {
          if ($("#heading").attr("name"))
            alert('Look, this is showing because it\'s not undefined');
          else
            alert('This would be called if it were undefined or is there but empty');
      });
      </script>
      <h1 id="heading" name="bob">Welcome!</h1>
      

      【讨论】:

      • 如果名称 attr 存在但为空字符串,则该属性将存在但测试将失败。
      【解决方案5】:

      聚会迟到了,但是...为什么不只是this.hasAttribute("name")

      参考This

      【讨论】:

      • 或者如果您不在乎它在许多旧浏览器和 IE 中不起作用
      【解决方案6】:

      最好的方法是使用filter()

      $("nav>ul>li>a").filter("[data-page-id]");
      

      拥有 .hasAttr() 还是不错的,但由于它不存在,所以有这种方式。

      【讨论】:

        【解决方案7】:
        Object.prototype.hasAttr = function(attr) {
            if(this.attr) {
                var _attr = this.attr(attr);
            } else {
                var _attr = this.getAttribute(attr);
            }
            return (typeof _attr !== "undefined" && _attr !== false && _attr !== null);      
        };
        

        我在编写自己的函数来做同样的事情时遇到了这个问题……我想分享一下,以防其他人在这里绊倒。 我添加了 null 因为如果属性不存在 getAttribute() 将返回 null。

        此方法将允许您检查 jQuery 对象和常规 javascript 对象。

        【讨论】:

          【解决方案8】:

          您还可以将其与表单字段上的 disabled="disabled" 等属性一起使用,如下所示:

          $("#change_password").click(function() {
              var target = $(this).attr("rel");
              if($("#" + target).attr("disabled")) {
                  $("#" + target).attr("disabled", false);
              } else {
                  $("#" + target).attr("disabled", true);
              }
          });
          

          “rel”属性存储目标输入字段的id。

          【讨论】:

            【解决方案9】:

            我为 jquery 编写了一个 hasAttr() 插件,它将非常简单地完成所有这些工作,完全按照 OP 的要求。更多信息here

            编辑: 我的插件在 2010 年的 plugins.jquery.com 数据库删除灾难中被删除。您可以查看 here 了解有关自己添加它的一些信息,以及为什么它没有被添加。

            【讨论】:

            • 有趣的是,这些链接在 IE 8 中不起作用,但在 Chrome 中……
            猜你喜欢
            • 2017-06-19
            • 2014-02-17
            • 2022-01-04
            • 2020-07-09
            • 1970-01-01
            • 2016-06-07
            • 2011-06-03
            • 2016-10-25
            相关资源
            最近更新 更多