在jQuery中如何检查元素上是否有属性?类似于hasClass,但与attr?

例如,

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

当前回答

如果你经常检查属性的存在,我建议创建一个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>

其他回答

你就差这么一点了,太疯狂了。

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

这里没有hasAttr,但是如果一个属性不存在,那么按名称点击它将返回undefined。

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

更新:根据评论,下面只会工作,如果属性是存在的,并被设置为一些东西,如果属性是空的

<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>

我为jquery写了一个hasAttr()插件,它将非常简单地完成所有这一切,正如OP所要求的那样。更多信息请点击这里

编辑: 我的插件在2010年的plugins.jquery.com数据库删除灾难中被删除。你可以在这里找到一些关于自己添加它的信息,以及为什么它没有被添加。

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) {
    // ...
}

来晚了,但是…为什么不只是this.hasAttribute("name")?

请参考这个

如果你经常检查属性的存在,我建议创建一个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>