jQuery的检查,如果元素包含任何属性 [英] jQuery check if element contains any attribute

查看:161
本文介绍了jQuery的检查,如果元素包含任何属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can check if an element have a specific attribute with:

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

我如何检查元素是否有什么属性?

How can I check if an element have any attribute?

感谢您

推荐答案

下面是决定任何一个选择匹配的元素是否至少有一个属性的功能:

Here's a function that determines whether any of the elements matching a selector have at least one attribute:

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;
}

用法:

if (hasOneOrMoreAttributes('.someClass')) {
    // Do something
}

如果你想上至少有一个属性选择元素进行操作,那就更简单了 - 你创建一个自定义过滤器:

If you want to operate on selected elements that have at least one attribute, it's even easier - you create a custom filter:

// 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;
};

您可以使用这样的:

Which you can use like this:

$(document).ready(function(){
    $('li:hasAttributes').addClass('superImportant');
}

这篇关于jQuery的检查,如果元素包含任何属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆