已解决-我的代码没有在所有应该使用的地方使用var。添加此项可以解决问题。
我正在尝试使用一个循环来遍历给定"场景"的子节点。在本例中,它是场景2。我的代码允许"链接",这些链接本质上是在返回到当前场景并加载其余子节点之前,先去加载另一个场景的子节点。问题是,每当我使用链接时,它都会阻止原始场景完成加载。
XML:
<scene id="2">
<content>Scene2-Content1</content>
<content>Scene2-Content2</content>
<link id="4"/>
<choice content="Scene2-Choice1"/>
</scene>
<scene id="4">
<content>Scene4-Content1</content>
<choice content="Scene4-Choice1"/>
</scene>
JavaScript:
var app = {
loadScene: function (scene) {
//find the scene and load the scene data
if(app.storyXml != null)
{
sceneNodes = app.storyXml.getElementsByTagName("scene");
for(i=0; i<sceneNodes.length; i++)
{
id = sceneNodes[i].getAttribute("id");
if(id == scene)
{
app.loadSceneData(sceneNodes[i]);
break;
}
}
}
},
loadSceneData: function (scene) {
childNodes = scene.childNodes;
try
{
length = childNodes.length;
for(i=0; i<childNodes.length; i++)
{
console.log((i+1)+"/"+childNodes.length);
tag = childNodes[i].tagName;
if(tag == "content")
app.loadSceneContent(childNodes[i]);
if(tag == "link")
app.loadSceneLink(childNodes[i]);
if(tag == "choice")
app.loadSceneChoice(childNodes[i]);
}
}
catch(err)
{
console.log(err);
}
},
loadSceneLink: function (node) {
if(app.storyXml != null)
{
sceneNodes = app.storyXml.getElementsByTagName("scene");
for(i=0; i<sceneNodes.length; i++)
{
id = sceneNodes[i].getAttribute("id");
if(id == node.getAttribute("id"))
{
app.loadSceneData(sceneNodes[i]);
break;
}
}
}
}
}
//loadSceneContent and loadSceneChoice omitted--they simply add some elements to the page.
在此特定示例中,将为场景2中的前两个内容节点调用loadSceneContent/loadSceneChoice。之后,链接会为内容/选择节点调用它们。我希望控件返回到原始的loadSceneData循环,但它只是跳到原始loadSceneData调用中循环的末尾。我的头撞在墙上,尝试了我能想到的每一种变化。似乎什么都不管用。
如果移除链接节点,则场景2中的所有内容都将按预期加载。
我不经常在Stack Overflow上发帖,所以如果我的问题遗漏了一些重要内容,请告诉我。我感谢你的帮助!
用var
声明循环变量i
应该可以修复调用方法之间的任何冲突。在没有var
的情况下,i
被声明为全局变量。。。这意味着所有方法最终都将共享它的使用。如果每个方法都是单独调用的,但它们是在每个方法的循环中调用的,那也没关系。如果在另一个循环的中间调用一个方法,则i
的值将被修改,从而使包含的循环变得混乱。
举个例子,你的第一个循环应该是这样的:
for(var i=0; i<sceneNodes.length; i++)