在jQuery中如何检查元素上是否有属性?类似于hasClass,但与attr?
例如,
if ($(this).hasAttr("name")) {
// ...
}
在jQuery中如何检查元素上是否有属性?类似于hasClass,但与attr?
例如,
if ($(this).hasAttr("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。
其他回答
你也可以使用它的属性,如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。
最好的方法是使用filter():
$("nav>ul>li>a").filter("[data-page-id]");
有. hasattr()仍然很好,但因为它不存在,所以有这种方式。
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>