Javascript 循环内的事件处理程序 - 需要关闭吗? [英] Event handlers inside a Javascript loop - need a closure?
问题描述
我正在处理一些从别人那里接过来的 html 和 Javascript 代码.该页面每十秒重新加载一个数据表(通过异步请求),然后使用一些 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
事件时,似乎将相同的值传递给 onStatusChanged()
表中每个 的方法(我已经验证了在循环的每次迭代中,
callid
和 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()
?
我已更改标题以更好地反映问题和已接受的答案.
推荐答案
你确实需要在这里实现一个闭包.这应该工作(让我知道 - 我没有测试过)
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屋!