簡體   English   中英

JavaScript循環

[英]Javascript For-Loop

目前,我正在使用RaphealJS庫進行項目開發,在遇到類似問題之前,一切似乎都還不錯。

而不是多次這樣做:

   dolphinIcon[1].click(function() {              
           this.attr({  
             stroke: 'black', 'stroke-width': 2,  
             fill: 'green'  
           }); 
           alert(1);
   });

   dolphinIcon[2].click(function() {              
           this.attr({  
             stroke: 'black', 'stroke-width': 2,  
             fill: 'green'  
           }); 
           alert(2);
   });

  dolphinIcon[3].click(function() {              
           this.attr({  
             stroke: 'black', 'stroke-width': 2,  
             fill: 'green'  
           }); 
           alert(3);
   });

我為什么不能這樣做呢?

for(var i=0; i<dolphinIcon.length; i++){
     dolphinIcon[i].click(function() {              
        this.attr({  
           stroke: 'black', 'stroke-width': 2,  
           fill: 'green'  
        });      
        alert(i);
     });
}

我只希望存儲在數組中的每個圖標都可以alert()它的索引號,但是當我使用for循環時,無論我單擊哪個圖標,它都總是alert()相同號(數組的大小)。 。 我該如何解決?

這是一個經典的JavaScript問題。 每個回調函數中的變量i都是相同的,循環完成后將為dolphinIcon.length

您需要使用閉包來“捕獲” i變量。

var clickFunc = function(i){
    return function(){
        this.attr({  
           stroke: 'black', 'stroke-width': 2,  
           fill: 'green'  
        });      
        alert(i);
    }
};
for(var i=0; i<dolphinIcon.length; i++){
     dolphinIcon[i].click(clickFunc(i));
}

clickFunc將返回一個函數,該函數“關閉” i的值。

您還可以將額外的數據傳遞給click處理程序,以便在調用后使用。

for(var i=0; i<dolphinIcon.length; i++){
     dolphinIcon[i].click({i: i}, function(e) {              
        this.attr({  
           stroke: 'black', 'stroke-width': 2,  
           fill: 'green'  
        });      
        alert(e.data.i);
     });
}

這是因為javascript閉包的工作方式-基本上,您的回調/事件處理函數綁定到循環變量i,而不是在連續的循環迭代中綁定到i的特定值。

這是簡單的解決方法:只需用匿名函數包裝循環的內部,然后將循環變量傳遞給該函數。 這將導致閉包附加到該特定值。

例如:

for(var i=0; i<dolphinIcon.length; i++)
{
    (   function(i) 
        {
            dolphinIcon[i].click(function() 
            {              
                this.attr({ stroke: 'black', 'stroke-width': 2, fill: 'green'});      
                alert(i);
            } );
        } )( i );
}

嘗試這個:

for(var i=0; i<dolphinIcon.length; i++){ 
     dolphinIcon[i].bind('click', {index: i}, function(e) {             
        $(this).attr({   
           stroke: 'black', 'stroke-width': 2,   
           fill: 'green'   
        });       
        alert(e.data.index); 
     }); 
}

我想建議underscore.js庫。 它包含許多處理數組和onbject的實用程序方法(在您的情況下,每個對象都綁定) http://underscorejs.org/#each

在您的示例中,該代碼將簡化為:

_.each(dolphicons, function(dolphicon, index){  
    var func = function() {              
        this.attr({  
           stroke: 'black', 'stroke-width': 2,  
           fill: 'green'  
        });      
        console.log(index);
    }
    func = _.bind(func, dolphicon);

    dolphicon.click(func);
});

因為綁定,“ this”將指向海豚。 示例還可以在以下網址找到: http//jsfiddle.net/SyJdv/

您也可以在每個循環之外定義函數范圍

var func = function() {              
   this.obj.attr({  
      stroke: 'black', 'stroke-width': 2,  
      fill: 'green'  
    });      
    console.log(this.index);
}

_.each(dolphicons, function(dolphicon, index){  
   var clickfunc = _.bind(func, {obj: dolphicon, index: index});    
   dolphicon.click(clickfunc);
});

http://jsfiddle.net/PW9WX/1/

在這里,我為您提供了一個代碼鏈接,准備為您提供示例和有關以下方面的詳細信息:以三種不同方式對JavaScript進行循環,單擊鏈接以閱讀代碼,進行自我測試並提供一個類似的提示。

https://code.sololearn.com/WHc3WmA7TrMP

波紋管是代碼:

<!DOCTYPE html>
<html>
   <body>

      <script type="text/javascript">
         /*
        The For Loop. Bellow are three examples using the same code in different ways, 
        returning the same results. Before let's explain which are the components fo the for loop.

        for loop have 3 components:
        1.initialization 
        2.condition
        3.Iteration 

      syntax: for (Initialization;condition;iteration)

        e.g.: for (i=1; i<=5; i++)

        In JavaScript <br> this tag is used as a line break.
        */

        //The example below creates a for loop that prints numbers 1 through 5.
        document.write("The example below creates a for loop that prints numbers 1 through 5. <br/>");
        for (i=1; i<=5; i++) {
           document.write(i + "<br />"); // <br /> is use to line break
        }

        //Statement 1 is optional, and can be omitted, if your values are set before the loop starts.
        document.write("<br/> Statement 1 is optional, and can be omitted, if your values are set before the loop starts. <br/>");
        var i = 1;
        for (; i<=5; i++) {
           document.write(i + "<br />");
        }

        //Also, you can initiate more than one value in statement 1, using commas to separate them.
        document.write("<br/> Also, you can initiate more than one value in statement 1, using commas to separate them. <br/>");
        for (i=1, text=""; i<=5; i++) {
            text = i;
            document.write(text + "<br />");
        }

        /* 
        If you notice in the for loop in JavaScript is not mandatory to declare explicitly a variable.
        e.g.: for (i=1; i<=5; i++) {}

        this is equivalent to say:
        for (var i=1; i<=5; i++) {}

        */

        // the following code will generate an infinite loop if you do not include break;
        var i = 0;
        for (; ; ) {
            document.write(i);
            i++;
            // if you comment or delete the break, this for loop will never end
            break;
        }

      </script>

      <p>Please like this code, I hope it helps you to learn more about For Loop ...</p>
   </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM