我有一组带有生成ID的复选框,其中一些有额外的属性 . 是否可以使用JQuery来检查元素是否具有特定属性?例如,我可以验证以下元素是否具有属性“myattr”?属性的值可以变化 .
<input type="checkbox" id="A" myattr="val_attr">A</input>
例如,如何逐个检查具有此属性的所有复选框的集合?这可能吗?
你的意思是你可以选择它们吗?如果是,那么是:
$(":checkbox[myattr]")
if ($('#A').attr('myattr')) { // attribute exists } else { // attribute does not exist }
EDIT:
当 myattr 存在但是为空字符串或"0"时,上述内容将落入 else -branch . 如果这是一个问题,你应该在 undefined 上明确测试:
myattr
else
undefined
if ($('#A').attr('myattr') !== undefined) { // attribute exists } else { // attribute does not exist }
我知道问题问题已经很长时间了,但我发现支票更加清晰:
if ($("#A").is('[myattr]')) { // attribute exists } else { // attribute does not exist }
(在本网站上找到here)
有关 is 的文档可以在here找到
在JavaScript中,......
null == undefined
...返回 true * . 这是 == 和 === 之间的区别 . 此外,可以定义名称 undefined (它不是像 null 这样的关键字),所以你最好还是检查其他方式 . 最可靠的方法可能是比较 typeof 运算符的返回值 .
true
==
===
null
typeof
typeof o == "undefined"
然而,在这种情况下,与null相比应该起作用 .
*假设 undefined 实际上是未定义的 .
这将有效:
$('#A')[0].hasAttribute('myattr');
$("input[attr]").length 可能是更好的选择 .
$("input[attr]").length
使用“typeof”,jQuery“.is”和“.filter”时,有几个想法被抛出,所以我想我会发布一个快速的比较它们 . typeof似乎是最好的选择 . 虽然其他工作正常,但在为此工作调用jq库时似乎存在明显的性能差异 .
$("input#A").attr("myattr") == null
只是:
$('input[name*="value"]')
更多信息:official docs
if (!$("#element").attr('my_attr')){ //return false //attribute doesn't exists }
除了选择具有属性 $('[someAttribute]') 或 $('input[someAttribute]') 的所有元素之外,您还可以使用函数对对象执行布尔检查,例如在单击处理程序中:
$('[someAttribute]')
$('input[someAttribute]')
if(! this.hasAttribute('myattr') ) { ...
我已经创建了具有预期行为的npm包,如上所述 .
链接到[npm]和[github]
用法很简单 . 例如:
<p id="test" class="test">something</p> $("#test").hasAttr("class")
返回true .
也适用于camelcase .
JQuery将该属性作为字符串返回 . 因此,您可以检查该字符串的长度以确定是否已设置:
if ($("input#A").attr("myattr").length == 0) return null; else return $("input#A").attr("myattr");
13 回答
你的意思是你可以选择它们吗?如果是,那么是:
EDIT:
当
myattr
存在但是为空字符串或"0"时,上述内容将落入else
-branch . 如果这是一个问题,你应该在undefined
上明确测试:我知道问题问题已经很长时间了,但我发现支票更加清晰:
(在本网站上找到here)
有关 is 的文档可以在here找到
在JavaScript中,......
...返回
true
* . 这是==
和===
之间的区别 . 此外,可以定义名称undefined
(它不是像null
这样的关键字),所以你最好还是检查其他方式 . 最可靠的方法可能是比较typeof
运算符的返回值 .然而,在这种情况下,与null相比应该起作用 .
*假设
undefined
实际上是未定义的 .这将有效:
$("input[attr]").length
可能是更好的选择 .使用“typeof”,jQuery“.is”和“.filter”时,有几个想法被抛出,所以我想我会发布一个快速的比较它们 . typeof似乎是最好的选择 . 虽然其他工作正常,但在为此工作调用jq库时似乎存在明显的性能差异 .
只是:
更多信息:official docs
除了选择具有属性
$('[someAttribute]')
或$('input[someAttribute]')
的所有元素之外,您还可以使用函数对对象执行布尔检查,例如在单击处理程序中:if(! this.hasAttribute('myattr') ) { ...
我已经创建了具有预期行为的npm包,如上所述 .
链接到[npm]和[github]
用法很简单 . 例如:
返回true .
也适用于camelcase .
JQuery将该属性作为字符串返回 . 因此,您可以检查该字符串的长度以确定是否已设置: