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);
}

})();

4

2 回答 2

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);

演示

于 2013-06-28T17:06:17.203 回答
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);
    });
});

小提琴

于 2013-06-28T17:15:42.103 回答