Jquery无法理解这一点

alert(i) onclick绑定行在3个div上运行,但是单击时所有这些都会提醒i的最后一个设置值。 我希望我想做的事情有道理,很难解释。 它不会警告1,2或3,而是警告3,3,3。

 // Updates bar preview box this.updatePropertyMarkerBox = function(self, BarsID) { ... snip ... // Loop and add event handler for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) { // Add click event $("#bmi-" + self.containerId + "-" + i).bind('click', function() { alert(i); }); } 

当你在for循环中进行迭代时,你基本上给了i的地址,如果你在那个时刻在for循环中使用它,它将是预期的值,但是如果你以后使用它(例如单击事件)它将指向最终递增的值3.为了获得所需的效果,您可以创建一个匿名函数,如此

 for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) (function(i) { // Add click event $("#bmi-" + self.containerId + "-" + i).bind('click', function() { alert(i); }); })(i) 
  $("#bmi-" + self.containerId + "-" + i).bind('click', (function(i) { return function() { alert(i); }; })(i)); 

虽然你可以使用在循环中调用一个函数,创建一个新的变量作用域来捕获i的当前值,但另一种方法是简单地从元素的ID属性中取i值:

 for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) { $("#bmi-" + self.containerId + "-" + i).bind('click', function() { //grab the number from the ID of the element alert( /\d+$/.exec( this.id )[0] ); }); } 

示例: http //jsfiddle.net/UGQA7/

在切线上,将点击处理程序添加到多个标记的更好方法是将单击处理程序添加到其容器中。 HTML可能看起来像:

 
...
...
...

您可以使用通用HTML5 data- *属性来存储任意数据。

而JavaScript将是:

 // Updates bar preview box this.updatePropertyMarkerBox = function (self, BarsID) { ... snip ... // Add event handler $("#bmi-" + self.containerId).click(function (event) { var marker = $(event.target).attr("data-marker"); if (marker) { // Hey, it's a marker! alert(marker); } });