Why doesn't $.each() iterate through every item?

后端 未结 3 1245
有刺的猬
有刺的猬 2020-12-09 01:24

I have the following markup containing 10 pre elements with the class indent:




        
相关标签:
3条回答
  • 2020-12-09 01:49

    $.each iterates over a collection of data. Since you pass a String that have 7 chars, it will iterate for each char. See the example of use:

    $.each([52, 97], function(index, value) { 
      alert(index + ': ' + value); 
    });
    
    0 讨论(0)
  • 2020-12-09 01:53
    $.each(".indent", function(index){
    

    doesn't iterate over the elements of $('.indent') but over the ".indent" string whose length is 7 chars.

    See reference


    A more detailed explanation based on jQuery source code :

    jQuery first checks if the first parameter, obj (here your string), has a length :

    var ...
            length = obj.length,
            isObj = length === undefined || jQuery.isFunction( obj );
    

    Your string having a length (and not being a function), isObj is false.

    In this case, the following code is executed :

    for ( ; i < length; ) {
        if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
            break;
        }
    }
    

    So, given the function f, the following code

    $.each(".indent", f);
    

    is equivalent to

    for (var i=0; i<".indent".length; i++) {
        var letter = ".indent"[i];
        f.call(letter, i, letter);
    }
    

    (you can log the letters using var f = function(i,v){console.log(v)}; or be reminded one of the subtleties of call using var f = function(){console.log(this)};)

    0 讨论(0)
  • 2020-12-09 01:54

    You are iterating through the string, you should pass an object or an array to $.each method:

    $(function(){    
        $.each($(".indent"), function(index){
           alert(index);
        });    
    });
    
    0 讨论(0)
提交回复
热议问题