Upload the code directly
The code is as follows, the select all function is not easy to use
var _select_all = document.getElementById("select_all");
var _input = document.querySelectorAll("#shop_content ul input[type=checkbox]");
_select_all.addEventListener("click",function() {
for(var i = 0;i<_input.length;i++) {
_input[i].checked="checked";
}
})
Change a sentence
var _select_all = document.getElementById("select_all");
_select_all.addEventListener("click",function() {
var _input = document.querySelectorAll("#shop_content ul input[type=checkbox]");
for(var i = 0;i<_input.length;i++) {
_input[i].checked="checked";
}
})
Why does the code execute normally when _input is placed below? Can't we get external variables in the callback function according to the scope?
習慣沉默2017-05-19 10:36:59
var _select_all = document.getElementById("select_all");
var _input = document.querySelectorAll("#shop_content ul input[type=checkbox]");
console.log(_input);
_select_all.addEventListener("click",function() {
for(var i = 0;i<_input.length;i++) {
_input[i].checked="checked";
}
})
You will know if you take a look at the log. If it is undefined, you will know where the problem lies.
習慣沉默2017-05-19 10:36:59
One is to check the nodes in advance and cache them, and the other is to check the nodes in real time when clicking. If the node corresponding to the #shop_content ul input[type=checkbox] selector does not change, the two methods are the same, and the caching efficiency is relatively high. If the corresponding node may be deleted, added or replaced, the second method must be used to find the node in real time every time you click it