如何使用 jQuery 检查元素上是否存在属性?类似于 hasClass
,但是使用的是 attr
?
例如:
if ($(this).hasAttr("name")) {
// ...
}
如何使用 jQuery 检查元素上是否存在属性?类似于 hasClass
,但是使用的是 attr
?
例如:
if ($(this).hasAttr("name")) {
// ...
}
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) {
// ...
}
&&
是正确的。如果属性既不是undefined又不是false,则应继续执行if
语句。如果任何一个条件为false,它都应该跳过if
。在你反转代码的情况下(可能是为了返回或错误处理),你需要使用||
,因为你只想捕获任意一个条件匹配的情况。 - Roe只使用 $(this).is("[name]")
怎么样?
[attr]
语法是选择带有属性 attr
的元素的 CSS 选择器,.is()
检查它被调用的元素是否与指定的 CSS 选择器匹配。
.attr
的速度比较如何? - Eugen Konkov如果您经常需要检查属性是否存在,我建议创建一个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>
虽然来晚了,但...为什么不直接用this.hasAttribute("name")
呢?
参见这里
最好的方法是使用filter()
函数:
$("nav>ul>li>a").filter("[data-page-id]");
虽然没有.hasAttr()方法,但是这种方式仍然很好用。
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对象。
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});