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

例如,

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

当前回答

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

请参考这个

其他回答

你也可以使用它的属性,如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。

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

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

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

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