伙计们!今天我创建了这个脚本,它具有以下功能:
- 将新项目添加到数组
- 列出数组中的所有项目
- 从数组中删除一个项目
有两个功能:
- addToFood() - 将输入值添加到数组并更新 div 的 innerHTML
- removeRecord(i) - 从数组中删除一条记录并更新 div 的 innerHTML
该代码包括 3 个 for 循环,您可以在 - http://jsfiddle.net/menian/3b4qp/1/看到它
我的主人告诉我,这 3 个 for 循环使解决方案变得繁重。有没有更好的方法来做同样的事情?减少循环并尝试使用拼接会更好吗?提前致谢。
HTML
<!-- we add to our foodList from the value of the following input -->
<input type="text" value="food" id="addFood" />
<!-- we call addToFood(); through the following button -->
<input type="submit" value="Add more to food" onClick="addToFood();">
<!-- The list of food is displayed in the following div -->
<div id="foods"></div>
JavaScript
var foodList = [];
function addToFood () {
var addFood = document.getElementById('addFood').value;
foodList.push(addFood);
for (i = 0; i < foodList.length; i++) {
var newFood = "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
};
document.getElementById('foods').innerHTML += newFood;
}
function removeRecord (i) {
// define variable j with equal to the number we got from removeRecord
var j = i;
// define and create a new temporary array
var tempList = [];
// empty newFood
// at the end of the function we "refill" it with the new content
var newFood = "";
for (var i = 0; i < foodList.length; i++) {
if(i != j) {
// we add all records except the one == to j to the new array
// the record eual to j is the one we've clicked on X to remove
tempList.push(foodList[i]);
}
};
// make redefine foodList by making it equal to the tempList array
// it should be smaller with one record
foodList = tempList;
// re-display the records from foodList the same way we did it in addToFood()
for (var i = 0; i < foodList.length; i++) {
newFood += "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
};
document.getElementById('foods').innerHTML = newFood;
}