【发布时间】:2021-02-24 17:36:36
【问题描述】:
我最近在这里获得了一些帮助,可以根据其在此列表中的位置通过文本删除 li 标记。现在,当将该脚本与我的整个代码放在一起时,它不再按预期工作。目标是能够将新的 li 条目添加到我的列表中(添加到已经存在的 4 个),然后能够通过文本框中的用户输入删除新条目。问题是,假设我添加了 3 个新的 li 标签,在此之后,我无法删除正确的 li 标签(即,如果有 5 个元素,我输入 5 来删除 li 标签 5,但没有任何反应)。我在想添加新的 li 标签后,它们不会被识别为预设列表的一部分。
<html>
<head>
<title>Chapter 5 Activity</title>
</head>
<body>
<h1>The Best Fruit in the World</h1>
<ol id="fruit">
<li>Mangos</li>
<li>Watermelons</li>
<li>Kiwis</li>
<li>Pineapples</li>
</ol>
<form action="">
<input type="text" name="afruit" id="fruitadd">
<input type="button" value="Click to Add" onclick="addfruit()">
Add your favorite fruit to the list<br>
<input type="text" name="rfruit" id="fruitremove">
<input type="button" value="Click to Remove" onclick="removefruit()">
Remove fruit you dislike
</form>
<script type="text/javascript">
function addfruit() {
var fruit1 = document.getElementById("fruitadd").value;
var newfruit = document.createElement("li");
newfruit.innerHTML = fruit1;
var flist = document.getElementById("fruit");
flist.insertBefore(newfruit, flist.childNodes [0]);
}
function removefruit(){
var fruitminus = document.getElementById("fruitremove").value;
var flist = document.getElementById("fruit");
if(fruitminus < (flist.childNodes.length)/2)
flist.removeChild(flist.childNodes[2*fruitminus-1]);
}
</script>
</body>
</html>
【问题讨论】:
-
所以用户必须输入水果名称才能删除它?尝试在您尝试删除列表项的 if 语句中添加此行。 console.log(flist.childNodes.length);查看错误信息。
-
我得到“参数 1 不是对象”,也许它与其他用户告诉我的内容有关,使用“childNodes”按“text, li,文字、李等”。
标签: javascript html-lists getelementbyid removechild createelement