jQuery hasAttr checking to see if there is an attribute on an element

Possible Duplicate:
Check existence of an attribute with JQuery

How do you check if there is an attribute on an element in jQuery? Similar to hasClass , but with attr ?

For example,

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

How about just $(this).is("[name]") ?

The [attr] syntax is the CSS selector for an element with an attribute attr , and .is() checks if the element it is called on matches the given CSS selector.


如果你经常检查属性的存在,我会建议创建一个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/14642.html

上一篇: 禁用停用选择选项标题

下一篇: jQuery hasAttr检查一个元素是否有属性