如何使用document.querySelectorAll遍历选定的元素 [英] How to loop through selected elements with document.querySelectorAll

查看:297
本文介绍了如何使用document.querySelectorAll遍历选定的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用document.querySelectorAll查询所选元素的循环,但是如何执行? 例如,我使用:

  var checkboxes = document.querySelectorAll('。check'); 
(我在复选框中){
console.log(复选框[i]);
}

输出:

 < input id =check-1class =checktype =checkboxname =check> 
< input id =check-2class =checktype =checkboxname =check>
< input id =check-3class =checktype =checkboxname =check>
< input id =check-4class =checktype =checkboxname =check>
< input id =check-5class =checktype =checkboxname =check>
< input id =check-6class =checktype =checkboxname =check>
< input id =check-7class =checktype =checkboxname =check>
< input id =check-8class =checktype =checkboxname =check>
< input id =check-9class =checktype =checkboxname =check>
< input id =check-10class =checktype =checkboxname =checkchecked =>

10
item()
namedItem()

我的问题是,最后这个方法返回3个额外的项目。

解决方案

for in 循环不是推荐用于数组和类似数组的对象 - 你明白了原因。可以不仅仅是数字索引项目,例如长度属性或一些方法,但是中的会循环所有这些。 (var i = 0,len = checkboxes.length; i< len; i ++){
//使用复选框[i]
}

  for(var i = 0,element; element = checkboxes [i]; i ++){
//使用元素
}

如果数组中的某些元素可能是虚假的,则不能使用第二种方法),但可以更具可读性,因为您无需在任何地方使用 [] 符号。


I am trying loop on selected elements that queried with document.querySelectorAll, but how?

For example I use:

var checkboxes = document.querySelectorAll('.check');
for( i in checkboxes) {
  console.log(checkboxes[i]);
}

Output:

<input id="check-1" class="check" type="checkbox" name="check">
<input id="check-2" class="check" type="checkbox" name="check">
<input id="check-3" class="check" type="checkbox" name="check">
<input id="check-4" class="check" type="checkbox" name="check">
<input id="check-5" class="check" type="checkbox" name="check">
<input id="check-6" class="check" type="checkbox" name="check">
<input id="check-7" class="check" type="checkbox" name="check">
<input id="check-8" class="check" type="checkbox" name="check">
<input id="check-9" class="check" type="checkbox" name="check">
<input id="check-10" class="check" type="checkbox" name="check" checked="">

10
item()
namedItem()

My problem is that at the end this method returns 3 extra items. How can I properly do it?

解决方案

for in loop is not recommended for arrays and array-like objects - you see why. There can be more than just number-indexed items, for example the length property or some methods, but for in will loop through all of them. Use either

for (var i = 0, len = checkboxes.length; i < len; i++) {
    //work with checkboxes[i]
}

or

for (var i = 0, element; element = checkboxes[i]; i++) {
    //work with element
}

The second way can't be used if some elements in array can be falsy (not your case), but can be more readable because you don't need to use [] notation everywhere.

这篇关于如何使用document.querySelectorAll遍历选定的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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