简体   繁体   English

使用onclick时,coffeescript中的变量值不变

[英]Variable's value doesn't change in coffeescript when using onclick

I have the following Coffeescript code: 我有以下Coffeescript代码:

for name, data of statistics
    row = document.createElement 'tr'
    row.onclick = ->
        alert name

However, when I compile and run it (in the context of a large webpage), it alerts the same name, no matter what row I click on. 但是,当我编译并运行它时(在大型网页中),无论单击什么行,它都会发出相同的名称警报。 It seems to be remembering the variable, as if it's constant. 似乎在记住该变量,就好像它是常量一样。

What am I doing wrong? 我究竟做错了什么?

EDIT: 编辑:

I've discovered the issue, but I'm not sure how to go about fixing it: Javascript/Coffeescript does not evaluate the 'name' variable until the end of the loop is reached. 我已经发现了这个问题,但是我不确定该如何解决:在循环结束之前,Javascript / Coffeescript不会评估'name'变量。

The functions that you are defining (and assigning to the row's onclick attribute) all have access to the same variable outside that function (name). 您正在定义(并分配给行的onclick属性)的函数都可以访问该函数(名称)之外的同一变量。 At the end of the loop, name has one value (the last item in the loop, as you mention), so each of the onclick functions alerts that value. 在循环的最后,名称具有一个值(如您所述,循环中的最后一项),因此每个onclick函数都会提醒该值。

You can fix this by binding 'name' to a value that doesn't change. 您可以通过将“名称”绑定到不变的值来解决此问题。 This question presents one solution. 这个问题提出了一个解决方案。 This question has some useful background that's worth reading. 这个问题有一些有用的背景,值得一读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM