在javascript中是否存在以下jquery代码的直接等价物?
$('.checkbox').each(function() {
if ($(this).is(':checked')) {
//logic here
}
});
Run Code Online (Sandbox Code Playgroud)
我正试图浏览页面上的所有复选框class = 'checkbox'- 客户端不想使用jQuery,所以我需要上面的替代方案.
我希望我可以避免从头开始编写一个很长的函数来完成这个并简单地使用内置于JavaScript的东西,但看起来它是不可能的.
许多旧版浏览器不支持querySelectorAll或者getElementsByClassName,因此您必须遍历<input>这些浏览器中的所有元素.不过,最好先检查这些功能.
其次,你永远不应该使用$(this).is(":checked")- 甚至在jQuery中 - 在寻找时它是一条非常慢的路径this.checked.
这应该让你去:
var base = document,
inps, tmp, i = 0, reg = /\bcheckbox\b/;
// getElementsByClassName is the fastest method
if (base.getElementsByClassName)
inps = base.getElementsByClassName("checkbox");
// Followed by querySelectorAll
else if (base.querySelectorAll)
inps = base.querySelectorAll(".checkbox");
// But if neither exist, loop through all the elements and check the class
else {
inps = [];
var tmp = base.getElementsByTagName("input");
i = tmp.length;
while (i--) {
if (reg.test(tmp[i].className)
inps.push(tmp[i]);
}
}
// Finally, loop through the matched elements and apply your logic
i = inps.length;
while (i--) {
var current = inps[i];
if (current.checked) {
// logic here
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,您可以更改base任何元素的值.这意味着,如果所有这些元素都具有公共父节点或祖先节点,则可以将该元素设置为基础,并且它应该运行得更快,例如:
var base = document.getElementById("myForm");
Run Code Online (Sandbox Code Playgroud)