2013-06-28 98 views
1

我有一个创建的函数,我希望将id传递到动态单击事件处理程序中。该对象不见了,计数器值始终是最后一个增量值。我认为有一种方法可以让它通过,但我无法弄清楚。将外部引用添加到动态事件处理程序

这里是我的演示代码... http://jsfiddle.net/ryanoc/r62jJ/

任何帮助是极大的赞赏。

(function(){ 
$('#chartContainer').empty().attr("style", "overflow: hidden;"); 
var office = []; 
var len = 5; 
for (var i = 0; i < len; i++) { 
    var obj = { 
     officeTitle: 'Office:'+i, 
     officeId: i, 
     resizeable: true 
    }; 
    office.push(obj); 
} 

for (var i = 0; i < office.length; i++) { 

    var chartHtml = $("<div>") 
    .attr("id", "chartContainer" + i) 
    .attr("style", "margin-top:20px;"); 

    $('#chartContainer').append(chartHtml); 

    var officeLabel = $("<div>") 
    .attr("style", "background-color:#eee;cursor:pointer;") 
    .html(office[i]["officeTitle"] + ':' + office[i]["officeId"]) 
    .click(function(){ 
     alert(i); 
     alert(office[i]["officeId"]) 
    }); 

    $('#chartContainer' + i).append(officeLabel); 
} 

})();

回答

1

你可以做

(function(index) { 
    var officeLabel = $("<div>") 
     .attr("style", "background-color:#eee;cursor:pointer;") 
     .html(office[index]["officeTitle"] + ':' + office[index]["officeId"]) 
     .click(function(){ 
      alert(office[index]["officeId"]) 
     }); 
    $('#chartContainer' + index).append(officeLabel); 
})(i); 

DEMO

+0

很不错的。我没有想过再添加一个封闭。我最终确定了一个将动态对象作为第一个参数添加到点击处理程序的解决方案...... http://jsfiddle.net/8aNmt/ – RyanOC

1

这里就是我想要做的:

$(function(){ 
    $('#chartContainer').empty().css('overflow', 'hidden'); 

    $.each([0,1,2,3,4], function(i, num) { 
     var chartHtml = $('<div>', {id: 'chartContainer' + num, style: 'margin-top : 20px'}), 
      officeLabel = $("<div>", {style: 'background-color:#eee; cursor:pointer;', 
             html : 'Office'+ num + ':' + num, 
             on: { 
              click: function(event) { 
               alert(num); 
              } 
              } 
            }); 

     $('#chartContainer').append(chartHtml); 
     $('#chartContainer' + num).append(officeLabel); 
    }); 
}); 

FIDDLE

相关问题