检查不存在的 child 值?
Checking value of child that doesn't exist?
我的html代码包含一个<ul id="users"></ul>
,然后用JS代码动态填充
const li = document.createElement("li");
li.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`)
我在 html 代码中添加了一个按钮来删除 <ul>
中的所有用户,例如:<button class="btn" id="del-user-list" onClick="deleteUserList()">Delete User List</button>
.
我在 JS 代码中的 deleteUserList 函数如下所示:
function deleteUserList() {
while (userList.firstChild != "") {
userList.firstChild.remove();
}
}
这在表面上有效,但我意识到在最后一个 child 之后,我的函数将再次检查不存在的 child 的值。我记得在学习 C 和玩链表时,您不想取消引用指向 null
.
的指针
果然,当我查看控制台时,我得到了
Uncaught TypeError: Cannot read properties of null (reading 'remove') at deleteUserList (main.js:31:25) at HTMLButtonElement.onclick ((index):29:77)
这是个问题吗?我该怎么办?我刚开始玩 Javascript,现在还不太了解这些东西是如何工作的。
不要将 userList.firstChild
与空字符串进行比较,而应将其与 null
进行比较或完全省略比较运算符:
while (userList.firstChild != null)
// or
while (userList.firstChild)
后一个有效,因为将 null
转换为布尔值 returns false
null != ''
将永远是 true
因为 userList.firstChild
永远不会是空字符串。它将是 DOM 节点或 null
.
我的html代码包含一个<ul id="users"></ul>
,然后用JS代码动态填充
const li = document.createElement("li");
li.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`)
我在 html 代码中添加了一个按钮来删除 <ul>
中的所有用户,例如:<button class="btn" id="del-user-list" onClick="deleteUserList()">Delete User List</button>
.
我在 JS 代码中的 deleteUserList 函数如下所示:
function deleteUserList() {
while (userList.firstChild != "") {
userList.firstChild.remove();
}
}
这在表面上有效,但我意识到在最后一个 child 之后,我的函数将再次检查不存在的 child 的值。我记得在学习 C 和玩链表时,您不想取消引用指向 null
.
果然,当我查看控制台时,我得到了
Uncaught TypeError: Cannot read properties of null (reading 'remove') at deleteUserList (main.js:31:25) at HTMLButtonElement.onclick ((index):29:77)
这是个问题吗?我该怎么办?我刚开始玩 Javascript,现在还不太了解这些东西是如何工作的。
不要将 userList.firstChild
与空字符串进行比较,而应将其与 null
进行比较或完全省略比较运算符:
while (userList.firstChild != null)
// or
while (userList.firstChild)
后一个有效,因为将 null
转换为布尔值 returns false
null != ''
将永远是 true
因为 userList.firstChild
永远不会是空字符串。它将是 DOM 节点或 null
.