【发布时间】:2014-07-05 21:47:55
【问题描述】:
我有这段无法工作的 javascript。它应该接受用户输入并将其存储到玩家输入变量中。然后,它拆分返回的字符串并将其拆分为一个数组,然后由函数 oc() 将其转换为一个对象。最后,analyzeUserInput 函数在输入对象中查找关键字,并将文本相应地放入称为文本的段落元素中。在这个例子中,如果用户输入斜线、戳、切片、黑客等,并且“剑”这个词,段落元素应该说“你做了 4 次伤害!”但事实并非如此。这是代码:
<!DOCTYPE html>
<html>
<body>
<p>"oh no theres a monster whatchya gonna do?"</p>
<input id="plyrInput" type="text" />
<button onclick="analyzeUserInput()">Try it</button>
<p id="text"></p>
<script>
var plyrInput;
var plyrInputArray;
var plyrInputAnalysis;
function oc() {
plyrInputArray = plyrInput.split(' ');
var plyrInputObj = {};
for (var i = 0; i < plyrInputArray.length; ++i) {
plyrInputObj[plyrInputArray[i]] = ' ';
}
return plyrInputObj;
}
function analyzeUserInput() {
plyrInput = document.getElementById("plyrInput").text;
oc();
if (plyrInputAnalysis in oc(['use', 'slash', 'hack', 'wield', 'slice', 'sever', 'dismember', 'poke', 'cripple', 'maim', 'mutilate', 'chop', 'rend']) && plyrInputAnalysis in oc(['sword'])) {
document.getElementById("text").innerHTML = "You did 4 damage with your sword!";
}
}
</script>
</body>
</html>
【问题讨论】:
-
HTML 文档需要一个
<head>元素。您可以使用W3C validator 来验证您的代码 -
这与 OPs JS 无法正常工作的原因无关
-
@EasyBB - 这就是为什么他在评论中提到它,而不是在答案中。
-
好吧,我只是说,因为我知道我不会为一个 JS 问题发布我所有的 HTML,只是一个 sn-p
-
老实说,我不明白你为什么调用
oc一次没有参数,一次调用一个未使用的参数。为什么你甚至想调用它两次?而plyrInputAnalysis永远不会被赋值。
标签: javascript dataflow