Dom 元素 onclick(MooTools:: 可选)
考虑以下示例:
function async_callback(array1, array2, array3) {
// All arrays are equal length
for(var i = 0; i < array1.length; i++) {
var myElement = new Element('div', { 'id': 'dvMy' + i, 'events': { 'click': function() { SomeFunction(array1[i], array2[i], array3[i] } }});
$(document).appendChild(myElement);
}
}
现在,当我单击元素时,所有三个参数都为空值。 我什至尝试这样做:
myElement.onclick = SomeFunction; // but this won't allow arguments
我知道我可以创建一个字符串并使用eval()
,这确实有效,但我不喜欢eval()
。
有什么想法吗?
顺便说一句:这是一个复制问题的简单示例,而不是实际代码。
Consider the following example:
function async_callback(array1, array2, array3) {
// All arrays are equal length
for(var i = 0; i < array1.length; i++) {
var myElement = new Element('div', { 'id': 'dvMy' + i, 'events': { 'click': function() { SomeFunction(array1[i], array2[i], array3[i] } }});
$(document).appendChild(myElement);
}
}
Now when I click my element, I get a null value for all three arguments.
I even tried doing:
myElement.onclick = SomeFunction; // but this won't allow arguments
I know I can create a string and use eval()
and that does work, but I don't like eval()
.
Any ideas?
BTW: This is a simple example to replicate the problem, and not actual code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是您的处理程序:
执行时,循环将完成,因此根据条件语句 (< code>i < array1.length) 和迭代语句 (
i++
)。解决此问题的最简单方法是将处理程序包装在一个附加的立即执行函数中,并将
i
传递给它,——这将具有保留i
值的效果。 code> 在一个新的闭包中:This is your handler:
By the time its executed, the loop will have completed and
i
will therefore be equal to thelength
of the array, as per the conditional statement (i < array1.length
) and the iteration statement (i++
).The easiest way to resolve this is to wrap the handler in an additional immediately-executed function, and pass
i
to it, -- this will have the effect of retaining the value ofi
in a new closure:这是一个经典例子:当
click
处理程序运行时,i
设置为循环中达到的最后一个值,在本例中为array1.length< /代码>。为了得到你想要的,你需要调用一个函数来创建点击处理程序并向其传递
i
的值:This is a classic: when the
click
handler runs,i
is set to the last value it reached in the loop, which in this case isarray1.length
. To get what you want, you need to call a function to create the click handler and pass it the value ofi
: