gpt4 book ai didi

javascript - 使用子节点更改文本

转载 作者:行者123 更新时间:2023-12-01 16:03:54 25 4
gpt4 key购买 nike

我一直在学习 javascript 和子节点。作为练习,我们必须通过使用父节点将列表项的文本切换为大写。

现在,它似乎将 javascript 中的值添加到列表中,而不是更改它们。只需要改变原来的文本值即可。

我认为我已经很接近了,但是我得到了一些奇怪的结果(当我在没有子节点的情况下这样做时不会发生这种情况)。这可能是一件小事,但我仍然感谢任何人来看一看!

JavaScript

addEventListener("load",init,false);

function init(){
let span = document.getElementsByClassName("aantal");
span[0].innerHTML = "3";

let node = document.getElementsByClassName("list")[0].parentNode;
node.firstChild.nodeValue = "ROOD";
node.childNodes[1].nodeValue = "GROEN";
node.childNodes[2].nodeValue = "BLAUW";

}

html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Slides Opdracht04</title>
<link href="style/stijl.css" rel="stylesheet" />
<script src="js/demo4.js"></script>
</head>
<body>
<p>Kleuren</p>
<ul>
<li class="list">Rood</li>
<li class="list">Groen</li>
<li class="list">Blauw</li>
</ul>
<p>De lijst bevat <span class="aantal"></span> kleuren</p>
</body>
</html>

最佳答案

让我们更仔细地检查那些childNodes

const childNodes = document.querySelector('#parent').childNodes

console.log('Total', childNodes.length)
console.log([...childNodes]
.map(({ nodeType, textContent, nodeValue }) => ({ nodeType, textContent, nodeValue })))
<ul id="parent">
<li class="list">Rood</li>
<li class="list">Groen</li>
<li class="list">Blauw</li>
</ul>

从输出中可以看出,#parent 有 7 个 childNode,而不是您预期的 3 个。四个是“nodeType:3”,这意味着它们是文本节点。如您所见,它们只包含空格。剩下的 3 个是“nodeType: 1”,这意味着它们是 HTML 元素。这些是 li child 。

当您设置节点 0..2nodeValue 时,您实际上是在前 2 个空白文本节点加上一个 。设置 HTML 元素的 nodeValue 是空操作,因此会被忽略。因此,你得到:

[0] WHITESPACE     => "ROOD"
[1] <li>Rood</li> => "GROEN" # no-op - nothing happens
[2] WHITESPACE => "BLAUW"
# other elements at indexes > 2 - out of scope, nothing happens

关于javascript - 使用子节点更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63471506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com