Confusion caused by javascript select all function
大家讲道理
大家讲道理 2017-05-19 10:34:59
0
5
498

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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(5)
黄舟

You can test both by yourself: https://jsfiddle.net/8j9q69qm/

洪涛

Tested it, both of them are OK

洪涛

No, it’s all the same

習慣沉默
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.

習慣沉默

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!