3 回答

TA贡献1828条经验 获得超13个赞
这比您尝试做的要简单得多。您可以直接按数字访问数组元素,无需循环。只需i从输入和输出中获取rimm[i]。
var rimm = ["Hej", "Nej", "EJ", "Leverpastej", "42"];
function getFunction() {
var i = document.getElementById("getnumber").value;
document.getElementById("skit").textContent = rimm[i];
}
<input type="text" id="getnumber">
<input type="button" value="Get" onclick="getFunction()">
<p>Skriv ut Skiten:</p><div id="skit"></div>
您可能需要检查数字是否有效以及是否在数组大小的范围内。我把这留给你。
注意:使用textContent比更好innerHTML,因为后者真正用于显示 HTML 编码的内容。除非这是您的意图,否则就是textContent要走的路。

TA贡献1853条经验 获得超6个赞
这是您可以采取的一种方法。我在用户输入上使用了一个事件处理程序和一些验证:
var words = ["Hej", "Nej", "EJ", "Leverpastej", "42"];
//Target our important elements
const userInputEl = document.querySelector('#userInput');
const outputEl = document.querySelector('#output');
//Fuction to validate the user input
const validateInput = input => {
if (isNaN(input)) {
outputEl.innerHTML = 'A number value is required!';
return false;
}
if (input > (words.length - 1)) {
outputEl.innerHTML = `The value must be between 0 and ${words.length - 1}`;
return false;
}
return true;
};
//Add an event listener that will fire when the value in the text input is changed
userInputEl.addEventListener('change', e => {
if (validateInput(e.target.value))
outputEl.innerHTML = words[e.target.value];
});
<input id="userInput" type="text">
<div id="output"></div>
添加回答
举报