javascript - 将 getElementById 更改为 getElementsByClassName [未定义]
问题描述
我在使用getElementsByClassName
. 单击添加按钮时,它会以 nameundefined
而不是 value出现在列表中"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>
解决方案
您的代码的主要问题是类名candidate
在您的 HTML 中的任何位置都不存在。如果您的目标是使用此类引用“添加”按钮,那么您需要candidate
在 HTML 中将其类更改为,或更改您的 JS 以引用其实际类,item
.
此外,getElementsByClassName
顾名思义,返回多个NodeList
元素的 a ,而不是单个元素。这意味着您需要从该列表中选择一个要对其进行操作的元素;相反,您的代码将此方法视为仅返回一个要直接操作的元素(即 a而不是 a )。对于您的功能,此更改是微不足道的;该类只有一个元素,因此只需选择(即 element )的第一个元素。对于该函数,假设您要首先删除最近添加的节点(LIFO 样式),您需要删除Node
NodeList
addItem
item
NodeList
0
removeItem
NodeList
(如果存在的话)来自 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>
推荐阅读
- sql - 具有空行的 SQL Server 中的 CASE
- javascript - 在 node.js 中重命名文件夹失败
- batch-file - 批量移动包含特定文件的文件夹
- hashcat - HashCat bcrypt $2*$, Blowfish (Unix) 行长异常
- android - 就像房间持久性库中区分大小写一样
- angularjs - 用数学 jax 渲染 html
- c# - 格式化由 [ ] 包围的 json writer 输出格式
- java - 如何设置匹配的消息?
- php - laravel - 交叉连接不返回所有列
- ruby-on-rails - ActiveRecord::ConcurrentMigrationError:使用 mysql2 和 rails 5.2