我对JavaScript的经验很少。
我的目标是从数组构建表,并允许用户根据需要从数组中删除项目。我想在显示的每个数组项旁边都有一个“删除”按钮。
我对实现此目标的其他想法持开放态度。我的代码在这里:
var LargeList = ["¥"]
function AddLargeItem() {
LargeList.push(document.getElementById("LargeItems").value)
LLen = LargeList.length;
text = "<ol>";
for (i = 0; i < LLen; i++) {
text += "<li>" + LargeList[i] + "</li>";
}
text += "</ol>";
document.getElementById("LargeInventory").innerHTML = text;
document.getElementById("LargeCount").innerHTML = LLen * 10;
document.getElementById("random").innerHTML = LargeList.join("/ ");
}
目标HTML:
<body>
<div>
<select id="LargeItems">
<option></option>
<option>LMIS</option>
<option>ARMC</option>
<option>BNCH</option>
</select>
<input type="button" onclick="AddLargeItem()" id="AddLargeItem" value="ADD LARGE" />
<span><p id="LargeCount"></p></span>
</div>
<p id="random"></p>
<p id="LargeInventory"></p>
</div>
我想在显示的每个数组项旁边有一个“删除”按钮
为了达到上述要求,您可以修改以下代码。
<script>
var LargeList = ["¥"]
function AddLargeItem() {
LargeList.push(document.getElementById("LargeItems").value)
PopulateList(LargeList);
}
function PopulateList(arr) {
LLen = arr.length;
text = "<ol>";
for (i = 0; i < LLen; i++) {
text += "<li>" + arr[i] + "<input type='button' onclick='Delitem(" + i + ")' value='Delete' /></li>";
}
text += "</ol>";
document.getElementById("LargeInventory").innerHTML = text;
document.getElementById("LargeCount").innerHTML = LLen * 10;
document.getElementById("random").innerHTML = arr.join("/ ");
}
function Delitem(index) {
LargeList.splice(index, 1);
PopulateList(LargeList);
}
</script>
测试结果
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句