我有一个javascript页面(function.js),该页面包含在我的game.php中,并且在functions.js中定义了一个数组。像这样:
var palavra=[];
function fun(){
var input=document.getElementById("palavra").value;
var letra1=input.charAt(0);
var letra2=input.charAt(1);
var letra3=input.charAt(2);
var letra4=input.charAt(3);
var letra5=input.charAt(4);
letra1=palavra[0];
letra2=palavra[1];
letra3=palavra[2];
letra4=palavra[3];
letra5=palavra[4];
}
此功能由game.php页面中的onclick事件触发:
<input id="palavra" type="text" name="palavra" maxlength="5">
<button onclick="fun()" id="btn"> Enviar</button>
我希望数组的每个索引都显示在html标签的中间,例如show bellow(也在game.php中)
<span class="letra"><script> palavra[0]</script></span>
<span class="letra"><script> palavra[1]</script></span>
<span class="letra"><script> palavra[2]</script></span>
<span class="letra"><script> palavra[3]</script></span>
<span class="letra"><script> palavra[4]</script></span>
但是,当我单击按钮时,什么也没有发生,并且出现以下错误:
Uncaught ReferenceError: palavra is not defined at game.php
Uncaught ReferenceError: fun is not defined at HTMLButtonElement.onclick (game.php)
我不明白为什么会这样,有人可以告诉我问题出在哪里。
答案 0 :(得分:1)
目前尚不清楚您要做什么,但是据我了解,您可以通过使用for-in
循环获取输入中的每个字符来实现您想要的目标。然后,您可以使用JavaScript通过执行document.body.innerHTML
来将每个字母/字符附加到文档中,而不使用HTML输入每个字母。
请参见下面的工作示例:
function fun() {
var input = document.getElementById("palavra").value;
for (i in input) {
document.body.innerHTML += '<br /><span class="letra">' + input[i] + '</span>';
}
}
<input id="palavra" type="text" name="palavra" maxlength="5" />
<button onclick="fun()" id="btn"> Enviar</button>
<!-- This will be generated using javascript-->
<!--span class="letra"><script> palavra[0]</script></span>
<span class="letra"><script> palavra[1]</script></span>
<span class="letra"><script> palavra[2]</script></span>
<span class="letra"><script> palavra[3]</script></span>
<span class="letra"><script> palavra[4]</script></span-->