我在使用getElementsByClassName
时遇到问题。单击添加按钮时,它会以名称undefined
而不是值"hello"
出现在列表中。我在做什么错了?
代码:
function addItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementsByClassName("candidate");
var li = document.createElement("li");
li.setAttribute('class',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
function removeItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementsByClassName("candidate");
var item = document.getElementsByClassName(candidate.value);
ul.removeChild(item);
}
<ul id="dynamic-list"></ul>
<button type="submit" class="item" value="hello" onclick="addItem()">ADD</button>
<button onclick="removeItem()">remove item</button>
答案 0 :(得分:0)
问题是您试图获取不存在的DOM元素candidate
的值。可能的解决方案可能是向按钮ADD添加ID属性,并在函数中获取此元素:
function addItem() {
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("item");
var li = document.createElement("li");
li.setAttribute('class', candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
<ul id="dynamic-list"></ul>
<button type="submit" class="item" id="item" value="hello" onclick="addItem()">ADD</button>
<button onclick="removeItem()">remove item</button>
答案 1 :(得分:0)
代码的主要问题是类名candidate
在HTML中不存在。如果您的目标是使用此类引用“ ADD”按钮,则您需要在HTML中将其类别更改为candidate
,或者将JS更改为引用其实际类item
。 / p>
此外,顾名思义,getElementsByClassName
返回的是{em>多个元素而不是单个元素的NodeList
。这意味着您需要从该列表中选择一个要操作的元素。相反,您的代码将这种方法视为仅返回要直接作用的单个元素(即Node
而不是NodeList
)。对于您的addItem
函数,此更改微不足道; item
类只有一个元素,因此只需选择NodeList
的第一个元素(即元素0
)。对于removeItem
函数,假设您要首先删除最近添加的节点(LIFO样式),则需要删除NodeList
中的 last 元素(如果存在)(来自DOM)。有关所有这些更改和一些说明性的注释,请参见下面的更新的代码段:
function addItem(){
var ul = document.getElementById("dynamic-list");
// We know that the "candidate" is always the first—and only—element with the class name "item"
var candidate = document.getElementsByClassName("item")[0];
var li = document.createElement("li");
li.setAttribute('class',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
function removeItem(){
var ul = document.getElementById("dynamic-list");
// We know that the "candidate" is always the first—and only—element with the class name "item"
var candidate = document.getElementsByClassName("item")[0];
// The "items" variable is introduced to hold the list of all added ".hello" elements, the last of which we will remove
var items = document.getElementsByClassName(candidate.value);
// Safety check: it's possible that there are no more ".hello" elements remaining, in which case there's nothing to remove
if (items.length > 0) {
// Access the last element of the NodeList and remove it from the DOM
var item = items[items.length - 1];
ul.removeChild(item);
}
}
<ul id="dynamic-list"></ul>
<button type="submit" class="item" value="hello" onclick="addItem()">ADD</button>
<button onclick="removeItem()">remove item</button>