Binding click event handlers in a loop causing problems in jQuery

隐身守侯 提交于 2019-12-04 04:00:18

问题


I am trying to run the following code:

I pass parameter to a function, but it always has the value of the last object run through the loop. I read some articles about it on stackoverflow, but I couldn't find out how to make it run in my solution.

The object is a JSON object returned from the server. All it's values are correct.

for(var i = 0;i<parents.length;i++){
            var row        = $(document.createElement("tr"));
            var colName    = $(document.createElement("td"));

            var aDisplayCol = $(document.createElement("a"));

            var parentId = parents[i]['PARENT_ID'];

            aDisplayCol.attr("href","#").html(parents[i]['NAME']);
            aDisplayCol.bind('click',function(){ alert(parentId);});


            colName.append(aDisplayCol);

            row.append(colName);
            $('#pages tbody').append(row);                

}

Thanks


回答1:


It is a scope problem. By the time the event handler function is executed, the value of parentId has changed and is not longer what you expected.

This can be solved making the original event handler function be returned by another function which, in turn, is passed the value of parentId as argument:

function getEventHandlerFunction(id){
    return function() {
        alert(id);  // variable found in the closure with the expected value
    };
}


aDisplayCol.bind('click', getEventHandlerFunction(parentId));



回答2:


Perhaps there's a problem with using parentId in the callback.

Try alert(parents[i]['PARENT_ID']);.

EDIT: Let's see if we can get around our scope issues with .data().

aDisplayCol.data("parentId",parents[i]['PARENT_ID']);
aDisplayCol.click(function() {
   alert($(this).data('parentId'));
});



回答3:


You can avoid the clouseres problems with the eventData parameter of the bind function like this

var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
    alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
    alert(event.data.msg);
});

this is from the jquery bind api documentation http://api.jquery.com/bind/#passing-event-data



来源:https://stackoverflow.com/questions/3531386/binding-click-event-handlers-in-a-loop-causing-problems-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!