3 回答

TA貢獻1828條經(jīng)驗 獲得超13個贊
這比您嘗試做的要簡單得多。您可以直接按數(shù)字訪問數(shù)組元素,無需循環(huán)。只需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>
您可能需要檢查數(shù)字是否有效以及是否在數(shù)組大小的范圍內(nèi)。我把這留給你。
注意:使用textContent比更好innerHTML,因為后者真正用于顯示 HTML 編碼的內(nèi)容。除非這是您的意圖,否則就是textContent要走的路。

TA貢獻1853條經(jīng)驗 獲得超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>
添加回答
舉報