繁体   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