我想让用户输入一串他们最喜欢的音乐艺术家的名字,但他们最多只能输入其中五个,然后在数组中使用这个字符串来显示用户的选择。 这是我的代码:
<div id="results">
<p id="resultsExpl"></p>
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
</div>
<form>
<fieldset>
<label for="plBox" id="placeLabel">
Please tell us!
</label>
<input type="text" id="placeBox" />
</fieldset>
<fieldset>
<button type="submit" id="artist">Submit</button>
</fieldset>
</form>
</article>
<script>
// new array to store entered music artists
var music = [];
// counter variable to track array indexes
var i = 0;
//function to add input to array and then generate list after 5th submission
// clear text box after submit
function processInput() {
document.getElementById("placeBox").value = ""
// add entered value to array
places[i] = document.getElementById("placeBox").value;
// write each array element to its corresponding list item
for (i = 0; i < 5; i++) {
listItem = "item" + i;
document.getElementById(listItem).innerHTML = places[i];
}
// iterate counter variable
if (i < 5) {
i++;
// add entered value to array and write results to document
} else {
listItem = "";
document.getElementById("resultsExpl");
document.write.innerHTML = "These are your favorite artists:" + listItem;
}
var submitButton = document.getElementById("artist");
document.addEventListener("click", processInput, false);
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
}
</script>
最佳答案
在函数的开头,您将清除该值,然后将其保存到地方变量中
document.getElementById("placeBox").value = ""
// add entered value to array
places[i] = document.getElementById("placeBox").value; // places[i] is just set to ""
因此它不断存储空白字符串(“”)
您还使用相同的变量“i”来迭代 for 循环,并用作到目前为止已填充多少位置的引用。
编辑1: 还有一些问题...
事件未附加到按钮。这是因为 AttachEvent 的代码位于函数“processInput”内,但 processInput 并未被调用。线条
var submitButton = document.getElementById("artist");
document.addEventListener("click", processInput, false);
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
需要在函数之外。
另一个问题是地方没有在全局范围内定义。您需要添加
var places = [];
在顶部 - 附近
var music = [];
var i = 0;
编辑 2——更多错误(第 2 部分)
列表项的 for 循环从 0 到 4,但 html 代码中的 id 是 1 到 5
我认为您的代码中有很多错误。您需要一点一点地编写它并不断测试您的代码,这样您就不会遇到这么多累积的错误。累积的错误使得调试变得非常困难。
关于javascript - 如何将用户输入应用到数组中最多五次,然后执行结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641000/