本文翻译自:jQuery hasAttr checking to see if there is an attribute on an element [duplicate]
Possible Duplicate: 可能重复:
Check existence of an attribute with JQuery 使用JQuery检查属性是否存在
How do you check if there is an attribute on an element in jQuery? 你如何检查jQuery中的元素是否有属性? Similar to hasClass
, but with attr
? 与hasClass
类似,但是attr
?
For example, 例如,
if ($(this).hasAttr("name")) {
// ...
}
#1楼
参考:https://stackoom.com/question/5WtI/jQuery-hasAttr检查元素是否有属性-重复
#2楼
You're so close it's crazy. 你太近了,这很疯狂。
if($(this).attr("name"))
There's no hasAttr but hitting an attribute by name will just return undefined if it doesn't exist. 没有hasAttr但按名称命中属性只会返回undefined(如果它不存在)。
This is why the below works. 这就是下面的原因。 If you remove the name attribute from #heading the second alert will fire. 如果从#heading中删除name属性,则会触发第二个警报。
Update: As per the comments, the below will ONLY work if the attribute is present AND is set to something not if the attribute is there but empty 更新:根据评论,如果属性存在,则以下将仅起作用并且如果属性存在但设置为不是,则设置为空
<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>
#3楼
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
// ...
}
#4楼
If you will be checking the existence of attributes frequently, I would suggest creating a hasAttr
function, to use as you hypothesized in your question: 如果您经常检查属性的存在,我建议创建一个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>
#5楼
The best way to do this would be with filter()
: 执行此操作的最佳方法是使用filter()
:
$("nav>ul>li>a").filter("[data-page-id]");
It would still be nice to have .hasAttr(), but as it doesn't exist there is this way. 拥有.hasAttr()仍然会很好,但因为它不存在就有这种方式。
#6楼
You can also use it with attributes such as disabled="disabled" on the form fields etc. like so: 您还可以在表单字段等上使用诸如disabled =“disabled”之类的属性,如下所示:
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});
The "rel" attribute stores the id of the target input field. “rel”属性存储目标输入字段的id。