jQuery hasAttr检查一个元素是否有属性
可能重复:
用JQuery检查是否存在属性
你如何检查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 !== typeof undefined && attr !== false) {
// ...
}
那么$(this).is("[name]")呢?
[attr]语法是具有属性attr的元素的CSS选择器, .is()检查它所调用的元素是否与给定的CSS选择器匹配。
如果你经常检查属性的存在,我会建议创建一个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>
链接地址: http://www.djcxy.com/p/14641.html
上一篇: jQuery hasAttr checking to see if there is an attribute on an element
