jQuery检查元素是否包含任何属性

Mir*_*cea 6 jquery attributes

我可以检查元素是否具有以下特定属性:

if ($('#A').attr('myattr') !== undefined) {
    // attribute exists
} else {
    // attribute does not exist
}
Run Code Online (Sandbox Code Playgroud)

如何检查元素是否具有任何属性?

谢谢

Poi*_*nty 9

如果要查看元素是否具有特定属性,请执行以下操作:

if ($('#something').is('[attribute]')) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*nal 6

这是一个函数,用于确定与选择器匹配的任何元素是否至少具有一个属性:

function hasOneOrMoreAttributes(selector) {
    var hasAttribute = false;
    $(selector).each(function(index, element) {
        if (element.attributes.length > 0) {
            hasAttribute = true;
            return false; // breaks out of the each once we find an attribute
        }
    });
    return hasAttribute;
}
Run Code Online (Sandbox Code Playgroud)

用法:

if (hasOneOrMoreAttributes('.someClass')) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

如果要对具有至少一个属性的选定元素进行操作,则更容易 - 您创建自定义过滤器:

// Works on the latest versions of Firefox, IE, Safari, and Chrome
// But not IE 6 (for reasons I don't understand)
jQuery.expr[':'].hasAttributes = function(elem) {
    return elem.attributes.length;
};
Run Code Online (Sandbox Code Playgroud)

您可以这样使用:

$(document).ready(function(){
    $('li:hasAttributes').addClass('superImportant');
}
Run Code Online (Sandbox Code Playgroud)