我将如何获得这项工作?我输入数字,然后将显示数组的内容。请参阅我的代码
var colorArray = ["Crimson", "Olive", "Red", "Yellow", "Black", "Beige", "Pink", "Orange"] = document.getElementById("enterNumber").value;
document.getElementById("btn").onclick = function() {
colorArray = document.getElementById("enterNumber").value;
document.getElementById("colorMagic").innerHTML = colorArray[enterNumber];
}
<p style="font-weight:bold; font-size:17px;">Please enter a <span style="color:red;">number</span>.</p>
<input id="enterNumber" class="textbox" type="text" value="" />
<button id="btn">Enter!</button>
<p id=""><span id="colorMagic">Crimson</span> is my new favorite color!</p>
答案 0 :(得分:3)
代码中的一些错误:
undefined
。总是更好地缓存元素对象,而不是每次都从DOM获取。
<input id="enterNumber" class="textbox" type="text" value="" />
<button id="btn">Enter!</button>
<p id=""><span id="colorMagic">Crimson</span> is my new favorite color!</p>
<script type="text/javascript">
var colorArray = ["Crimson", "Olive", "Red", "Yellow", "Black", "Beige", "Pink", "Orange"];
// cache elements object into varibales
var colorMagic = document.getElementById("colorMagic");
var numberInput = document.getElementById("enterNumber");
document.getElementById("btn").onclick = function() {
// get value from input
var val = numberInput.value;
// use || to handle if index is undefined
colorMagic.innerHTML = colorArray[val] || '(Not a valid index)';
}
</script>
&#13;