我有一个带有生成的ID的复选框集合,其中一些具有额外的属性。是否可以使用JQuery检查元素是否具有特定属性?例如,我可以验证以下元素是否具有属性“ myattr”吗?该属性的值可以变化。
<input type="checkbox" id="A" myattr="val_attr">A</input>
例如,如何一目了然地获取具有此属性的所有复选框的集合?这可能吗?
$filtered = $collection.filter('[attribute_name]');
我有一个带有生成的ID的复选框集合,其中一些具有额外的属性。是否可以使用JQuery检查元素是否具有特定属性?例如,我可以验证以下元素是否具有属性“ myattr”吗?该属性的值可以变化。
<input type="checkbox" id="A" myattr="val_attr">A</input>
例如,如何一目了然地获取具有此属性的所有复选框的集合?这可能吗?
$filtered = $collection.filter('[attribute_name]');
Answers:
您是说可以选择它们吗?如果是这样,那么是:
$(":checkbox[myattr]")
href属性的链接。$("#myBox").find('a').filter(':not([href])')
if ($('#A').attr('myattr')) {
// attribute exists
} else {
// attribute does not exist
}
编辑:
上面的内容存在else时将落入-branch,myattr但为空字符串或“ 0”。如果存在问题,则应在undefined以下位置进行显式测试:
if ($('#A').attr('myattr') !== undefined) {
// attribute exists
} else {
// attribute does not exist
}
undefined被认为是边缘情况,并且上面的比较将在所有情况的99%中起作用。
我知道问这个问题已经有很长时间了,但是我发现这样的支票更加清晰:
if ($("#A").is('[myattr]')) {
// attribute exists
} else {
// attribute does not exist
}
(如在此站点上找到的)
文档有关的,可以发现这里
这将起作用:
$('#A')[0].hasAttribute('myattr');
$(this).<something>在这里使用时可以this.hasAttribute('...')直接进行操作(当然,也不关心较旧的浏览器。)
在JavaScript中,...
null == undefined
...返回true*。==和之间的区别===。另外,undefined可以定义名称(它不是像nullis这样的关键字),因此最好检查一下其他方式。最可靠的方法可能是typeof比较运算符的返回值。
typeof o == "undefined"
不过,在这种情况下,将null与之比较应该可以。
*假设undefined实际上是未定义的。
if (!$("#element").attr('my_attr')){
//return false
//attribute doesn't exists
}
isset()或例如js $("#element").attr('my_attr') === false,
$("input#A").attr("myattr") == null
要选择具有特定属性的元素,请参见上面的答案。
为了确定给定的jQuery元素是否具有特定属性,我正在使用一个小插件,true该插件返回jQuery集合中的第一个元素是否具有此属性:
/** 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)
}
jQuery将以字符串形式返回属性。因此,您可以检查该字符串的长度以确定是否已设置:
if ($("input#A").attr("myattr").length == 0)
return null;
else
return $("input#A").attr("myattr");