【发布时间】:2016-04-15 22:12:29
【问题描述】:
我遇到的问题涉及服务器端 (JSP),因此我无法整理一个 jFiddle 示例,但我会尽我所能在此处尽可能简单地演示该问题:
首先,我有一个 JSP 页面,在页面顶部我导入了一个 javascript 文件,该文件包含一个 javascript 类,该类在页面上使用的次数不定。
所以下面的(import A)被导入到 JSP 页面的顶部以在页面内容中使用:
<script>
var TheJSClass = function(aValue, bValue) {
var me = this;
this.somePropertyA = aValue;
this.somePropertyB = bValue;
this.showValues = function() {
console.log("me.somePropertyA = " + me.somePropertyA);
console.log("me.somePropertyB = " + me.somePropertyB);
}
}
</script>
所以在 JSP 页面上只有一些 HTML:
<ul>
<li> blah blah blah
<!-- jsp import B here -->
</li>
<li> blah2 blah2 blah2
<!-- jsp import B here -->
</li>
</ul>
以下是导入B的示例
<!-- the unique_id is an attribute set on the page that I increment here at the top of this (import B) file this was my attempt to differentiate between the instances of the class within import A-->
<script>
var info<%=unique_id%> = new TheJSCLass(10,20);
</script>
<a href="" onclick="info<%=unique_id%>.showValues();">Try Me</a>
这一切似乎都有效......当我添加多个导入时会出现问题......例如,以下内容:
<!-- Another Import B -->
<script>
var info<%=unique_id%> = new TheJSCLass(30,40);
</script>
<a href="" onclick="info<%=unique_id%>.showValues();">Try Me</a>
然后是另一个:
<!-- Another Import B -->
<script>
var info<%=unique_id%> = new TheJSCLass(60,70);
</script>
<a href="" onclick="info<%=unique_id%>.showValues();">Try Me</a>
问题是,每个“Try Me”按钮都会显示上次导入的值,所以它们都将显示 60 70 作为值...我做错了吗?有什么建议吗?感谢大家的时间。
编辑:我刚刚制作了这个 jFiddle,它除了 JSP 将数字添加到每个变量名之外,其他所有内容都可以正常工作:
https://jsfiddle.net/vzo4fmjt/
那么这与我在每次导入期间添加到变量名的 JSP 编号有关吗?
【问题讨论】:
-
您应该检查标记并查看生成了哪些变量名称。
unique_id是否有可能永远不会更新? -
unique_id 肯定会更新,每个变量名称都有不同的数字(info0、info1、info2 等)我也在创建每个变量后立即控制台注销 showValues(),它们都以正确的值输出,但似乎一旦发生下一次导入,值就会以某种方式被覆盖,因为无论运行哪个 showValues()(info0.showValues() 或 info2.showValues())它总是输出最后一个创建的值。
标签: javascript jsp