MOOTOOLS 变量范围
我正在使用穆工具: 我不知道在使用 addEvent 时如何使用变量。
我想使用 for next 循环来设置循环中的值:
for (x=0;x<num;x++){
var onclickText = 'function (){onclick="addPageMoveEvent('+x+'"); }';
$('pageNum'+x).addEvent('click', onclickText);
}
>
我搜索过论坛但没有找到任何帮助。
任何帮助都会很棒。
谢谢
I'm using mootools:
I can't figure out how to use a variable when using an addEvent.
I want to use a for next loop to set values in a loop:
for (x=0;x<num;x++){
var onclickText = 'function (){onclick="addPageMoveEvent('+x+'"); }';
$('pageNum'+x).addEvent('click', onclickText);
}
>
I've search forums but not found any help.
Any help would be great.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MooTools 中的 addEvent 方法接受两个参数:
参数:
它不接受字符串,并且传递诸如
"myFunction()"
或"function() { myFunction(); }"
之类的字符串将不起作用。由于您位于循环内,并且变量 x 将共享环境,因此您需要将其值包装在另一个闭包中。一种方法是使用额外的闭包:
查看 StackOverflow 上有关在其中创建闭包的特定问题的所有问题循环。
另外值得一看的是这篇 MDC 文章 - 在循环中创建闭包:常见的错误
The addEvent method in MooTools accepts two arguments:
Arguments:
It does not take a string and passing a string such as
"myFunction()"
or"function() { myFunction(); }"
will not work.Since you are inside a loop, and the variable
x
will share the environment, you need to wrap its value inside another closure. One way is to use an additional closure:See all questions on StackOverflow regarding this particular problem of creating closures within loops.
Also worth checking out is this MDC article - Creating closures in loops: A common mistake
警告:第一个示例将不起作用!请继续阅读以获取解释。
您将
onclick
HTML 语法与 MooToolsaddEvent
混淆了。尝试一下,这更简单、更干净,但可能仍然达不到您想要的效果。每次单击链接时,此代码都会调用函数
addPageMoveEvent
...这是您想要的吗?由于 MooTools 不允许使用上述方法,因此您必须使用以下方法:
以编程方式实现相同目的的更有趣且危险性更小的方法是:
这使用工厂创建保存 x 值的闭包...相当复杂的代码,但这是最纯粹的方式。它还避免使用由于向
addEvent
提供字符串而发生的可怕的eval
。 (看来 MooTools 无论如何都不喜欢其他选项。)Warning: this first example will not work! Read on for an explanation.
You are confusing
onclick
HTML syntax with the MooToolsaddEvent
. TryThis is simpler and cleaner, but might still not do what you want. This code will call the function
addPageMoveEvent
every time the link is clicked... is that what you want?Since MooTools doesn't allow the above method, you must use the following:
A programmatically more interesting and less hazardous way to do the same would be:
This uses a factory for creating closures that hold your values of
x
... rather complex code, but it's the purist way. It also avoids using the scaryeval
that occurs because you feedaddEvent
a string. (It seems that MooTools doesn't like the other option anyway.)这是 mootools pass 方法的一个用例。
Pass 内部创建了一个闭包,将 x 保存在其范围内,因此当单击事件被触发时,它具有正确的值,因为它与 for 循环不同。
That a use case for mootools pass method.
Pass internally creates a closure that holds x in the his scope, so when the click event is fired it has the right value cause its not the same from the for loop.