Javascript循环中的事件处理程序 - 需要闭包? [英] Event handlers inside a Javascript loop - need a closure?

查看:92
本文介绍了Javascript循环中的事件处理程序 - 需要闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些我从别人那里接过的html和Javascript代码。页面每10秒重新加载一个数据表(通过异步请求),然后使用一些DOM代码重新构建表。有问题的代码看起来像这样:

I'm working with a bit of html and Javascript code that I've taken over from someone else. The page reloads a table of data (via an asynchronous request) every ten seconds, and then re-builds the table using some DOM code. The code in question looks something like this:

var blah = xmlres.getElementsByTagName('blah');
for(var i = 0; i < blah.length; i++) {
    var td = document.createElement('td');
    var select = document.createElement('select');
    select.setAttribute("...", "...");
    select.onchange = function() {
        onStatusChanged(select, callid, anotherid);
    };
    td.appendChild(select);
}

onchange 事件被触发为< select> 元素,但是,似乎相同的值被传递到 onStatusChanged() callid ),每个< select> c>和 anotherid 被赋予新的,不同的值)。

When the onchange event is fired for a <select> element however, it seems like the same values are being passed to the onStatusChanged() method for every <select> in the table (I've verified that in each iteration of the loop, callid and anotherid are being given new, distinct values).

我怀疑这是因为我设置事件处理程序的性质,使用 select.onchange = function()语法。如果我理解这是如何正确工作,这个语法设置一个闭包的onchange事件是一个函数,引用这两个引用,最终有一个最终的值,无论它们在循环的最后一次迭代。当事件触发时, callid anotherid 引用的值是最后一次迭代中设置的值,而不是值

I suspect this is occuring because of the nature of how I am setting the event handler, with the select.onchange = function() syntax. If I understand how this is working correctly, this syntax sets a closure for the onchange event to be a function which refers to these two references, which end up having a final value of whatever they are set to on the last iteration of the loop. When the event fires, the value referenced by callid and anotherid is the value set in the last iteration, not the value set at the individual iteration.

有一种方法,我可以复制参数的值传递给 onStatusChanged()

Is there a way that I can copy the value of the parameters I am passing to onStatusChanged()?

b

推荐答案

你确实需要在这里实现一个闭包。这应该工作(让我知道 - 我没有测试)

You do, indeed, need to implement a closure here. This should work (let me know - I didn't test it)

var blah = xmlres.getElementsByTagName('blah');
for(var i = 0; i < blah.length; i++) {
    var td = document.createElement('td');
    var select = document.createElement('select');
    select.setAttribute("...", "...");
    select.onchange = function(s,c,a)
    {
        return function()
        {
            onStatusChanged(s,c,a);
        }
    }(select, callid, anotherid);
    td.appendChild(select);
}

这篇关于Javascript循环中的事件处理程序 - 需要闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆