再次调用同一个 Play 模板时,变量的作用域如何?
我正在编写一个标签来跟踪它被调用的次数,以便为其元素生成唯一的 id:
%{
try {
coolTagId++;
} catch (Exception) {
coolTagId = 0;
}
}%
<div id='cool-tag-${coolTagId}'></div>
...
$('#cool-tag-${coolTagId}').click(function(){alert("Cool Tag ${coolTagId} clicked")});
当我在页面中多次包含此标签时,令我惊讶的是,我看到 coolTagId< /code> 每次计算时都是 0。为什么会发生这种情况?
(同时我将使用某种 UID,我只是想了解为什么上面的代码片段不起作用)
I'm writing a tag that keeps track of how many time it was called, in order to generate unique ids for its elements:
%{
try {
coolTagId++;
} catch (Exception) {
coolTagId = 0;
}
}%
<div id='cool-tag-${coolTagId}'></div>
...
$('#cool-tag-${coolTagId}').click(function(){alert("Cool Tag ${coolTagId} clicked")});
When I include this tag in a page multiple times, to my surprise, I see that coolTagId
is 0 every time it's evaluated. Why is this happening?
(I'll be using some sort of UID in the meantime, I just want to understand why the above snippet doesn't work)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道为什么会这样,但我并不感到惊讶。 Play 是一个无状态框架,因此它在相同标签的两个实例之间不共享状态似乎很自然。
有趣的是,即使使用
#{set CoolTagId:0 /}
预先设置值也不起作用。然而,真正有效的是在标签中设置值。将其放在标记的末尾:
#{set CoolTagId:coolTagId /}
。通过这种方式,您可以手动将值推送到基本模板。I don't know why that is but it doesn't surprise me. Play is a stateless framework, so it seems natural that it doesn't share state between two instances of the same tags.
It's interesting, even setting the value beforehand using
#{set coolTagId:0 /}
does not work.What does work however is setting the value in your tag. Put this at the end of your tag:
#{set coolTagId:coolTagId /}
. This way you manually push the value to the base template.这是一个简单的范围问题。
想象一下用纯 Java 编写的代码,标签实际上是在调用方法。标签中定义的所有内容(即方法)都在该标签的本地范围内,因此一旦执行标签,它就不会存在,因为它会离开范围。
这样做的原因是为了确保标签之外的任何内容不会因标签的执行而被破坏或修改。除了您传入的参数之外,一切都是独立的。
It is a simple matter of scope.
Imagine writing this in pure Java, a tag is effectively calling a method. Everything defined in your tag (i.e. method) is locally scoped to that tag, so it would not exist once the tag has been executed, as it would have left the scope.
The reason for this, is to make sure that anything outside of your tag is not broken or modified by the execution of your tag. Everything is self contained, except for the parameters that you pass in.