How to Add Event Handler with Arguments to an Array of Elements in Javascript?

匆匆过客 提交于 2019-12-05 05:12:51

Your closure scope chain is causing your problems. By declaring the handler function inline, you've created a closure. Obviously you did this to take advantage of the loop.

However, since you have created a closure, you're playing by closure scoping rules. Those rules state that the local variables within the parent function remain active and available as long as the closure exists.

You are trying to pass and then use "action" and "dao_id" to your closure, but you are passing references here, not values. So when your closures (handlers) are called they use the value that the reference was last assigned. In your case, the Step 3 handler.

Closure scoping rules are confusing enough, but you may also be confused by the fact that "action" and "dao_id" are still alive even though the loop block has finished executing. Well, in JavaScript there is no such thing as block scope. Once you declare a variable it is available until the end of the function or until is it deleted. Whichever comes first.

All that said, you need to break the scope chain. Here are two ways to do that:

Try this:

for (var i = 0; i < profile.current + 1; i++) {
    if ($('step_anchor_' + i).innerHTML.empty()) {
        var action = profile.steps[i].action;
        var dao_id = profile.steps[i].dao_id;

        $('step_anchor_' + i).innerHTML = profile.steps[i].anchor;
        $('step_anchor_' + i).observe('click', function(a, b){
                return function(){pm.loadData(a, b, true)};
        }(action, dao_id));

        Effect.Appear('step_anchor_' + i, {
                duration: 1,
                delay: (down_delay++)
        });
    }
}

Or this:

function createHandler(action, dao_id) {
    return function(){pm.loadData(action, dao_id, true);};
} 

/* snip - inside some other function */
for (var i = 0; i < profile.current + 1; i++) {
    if ($('step_anchor_' + i).innerHTML.empty()) {
        var action = profile.steps[i].action;
        var dao_id = profile.steps[i].dao_id;

        $('step_anchor_' + i).innerHTML = profile.steps[i].anchor;
        $('step_anchor_' + i).observe('click', createHandler(action, dao_id));
        Effect.Appear('step_anchor_' + i, {
                duration: 1,
                delay: (down_delay++)
        });
    }
}

First, remember your execution scope in the click event. The this keyword in that context refers to the element being clicked on. Is there any way you can determine the dao_id from the element that is clicked on?

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