2013-06-28 39 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

相關問題