我正在尝试创建一个包含主要内容 div 的页面,用户可以在其中选择不同的选项来添加不同的附加内容。添加的内容将提供添加更多不同内容的选项。最终目标是制作一个简短的互动故事。
经过编辑以反射(reflect)我仍然无法开始工作的部分新方法。
我当前的代码如下所示:
<div id="ongoingStory">
<p>You're standing in a place. There are whatever items here and one or more exits.</p>
<p>Do you want to take <span id="action1">action 1</span> or <span id="action 2">action 2</span>?</p>
</div>
var oneResult = "<p>You take action 1, and some stuff happens. You can then take <span id=\"action3\">action 3</span> or <span id=\"action4\">action 4</span>.</p>";
var anotherResult = "<p>You take action 2, and other stuff happens. You can then take <span id=\"action5\">action 5</span> or <span id=\"action6\">action 6</span>.</p>";
var root;
var branch;
function addToStory( root,branch ) {
$( "#" + root ).addClass( "disabled" );
$( branch ).appendTo( "#ongoingStory" ).hide().fadeIn(1000);
}
document.getElementById( "ongoingStory" ).addEventListener("click", moveAlong, false);
function moveAlong(e) {
if (e.target !== e.currentTarget) {
switch (e.target.id) {
case action1:addToStory( action1,oneResult );break;
case action2:addToStory( action2,anotherResult );break;
case action3:addToStory( action3,otherResult );break;
case action4:addToStory( action4,yetOtherResult );break;
};
};
e.stopPropagation();
}
页面加载没有任何错误,但是当我单击最初加载到 ongoingStory
div 中的内容中的操作时,没有任何反应。然后控制台告诉我“ReferenceError:action3 未定义。”当然不是,因为没有添加包含该 action/id 标签的内容。我不明白的是为什么它不首先附加内容。我想也许我没有正确引用 span 的 ID,但在那种情况下,我希望开关卡在 action1。
最佳答案
您的代码中存在不少问题。我们有covered the best practices in the chat room.至于实际问题,您遗漏了一些引号:
case action1:addToStory( action1,oneResult );break;
需要成为:
case 'action1':
addToStory('action1', oneResult);
break;
(所有其他操作相同)
这是一个 JSFiddle:http://jsfiddle.net/somekittens/70qebhbm/
关于javascript - 使用 appendTo() 和 switch 将变量中的内容添加到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837714/