Binding click event handlers in a loop causing problems in jQuery

前端 未结 3 695
一个人的身影
一个人的身影 2021-01-19 14:49

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 abou

3条回答
  •  情书的邮戳
    2021-01-19 15:26

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

提交回复
热议问题