我有一个生成id的复选框集合,其中一些有一个额外的属性。是否有可能使用JQuery来检查一个元素是否具有特定的属性? 例如,我能否验证以下元素是否具有属性“myattr”?属性的值可以变化。

<input type="checkbox" id="A" myattr="val_attr">A</input>

例如,我如何才能获得具有此属性的所有复选框的集合而不逐个检查?这可能吗?


当前回答

要选择具有特定属性的元素,请参阅上面的答案。

为了确定给定的jQuery元素是否具有特定的属性,我使用了一个小插件,如果ajQuery集合中的第一个元素具有此属性,则返回true:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}

其他回答

$("input#A").attr("myattr") == null

在这篇文章中,使用.is和属性选择器[],你可以很容易地添加一个函数(或原型):

function hasAttr($sel,attr) {
    return $sel.is('['+attr+']');
}

我知道这个问题已经问了很长时间了,但我发现答案是这样的:

if ($("#A").is('[myattr]')) {
    // attribute exists
} else {
    // attribute does not exist
}

(可以在这个网站上找到)

关于is的文档可以在这里找到

除了选择带有属性$('[someAttribute]')或$('input[someAttribute]')的所有元素外,您还可以使用一个函数对对象进行布尔检查,例如在单击处理程序中:

if (!这是他的功劳。

要选择具有特定属性的元素,请参阅上面的答案。

为了确定给定的jQuery元素是否具有特定的属性,我使用了一个小插件,如果ajQuery集合中的第一个元素具有此属性,则返回true:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}