search

Home  >  Q&A  >  body text

Confusion caused by javascript select all function

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?

大家讲道理大家讲道理2749 days ago509

reply all(5)I'll reply

  • 黄舟

    黄舟2017-05-19 10:36:59

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

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:36:59

    Tested it, both of them are OK

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:36:59

    No, it’s all the same

    reply
    0
  • 習慣沉默

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

    reply
    0
  • 習慣沉默

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

    reply
    0
  • Cancelreply