Javascript:文本节点
我正在使用W3school网站上的以下文章。当我在直线上使用LI元素时,效果很好。总线,因为我把它的格式,它不工作。有人有线索吗 这不起作用:Javascript:文本节点,javascript,Javascript,我正在使用W3school网站上的以下文章。当我在直线上使用LI元素时,效果很好。总线,因为我把它的格式,它不工作。有人有线索吗 这不起作用: <ul id="myList"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <p>Click the button to replace the first item
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<p>Click the button to replace the first item in the the list.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var textnode = document.createTextNode("Water");
var item = document.getElementById("myList").childNodes[0];
item.replaceChild(textnode, item.childNodes[0]);
}
</script>
- 咖啡
- 茶
- 牛奶
单击按钮以替换列表中的第一项
试试看
函数myFunction(){
var textnode=document.createTextNode(“水”);
var item=document.getElementById(“myList”).childNodes[0];
item.replaceChild(textnode,item.childNodes[0]);
}
这项工作:
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<p>Click the button to replace the first item in the the list.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var textnode = document.createTextNode("Water");
var item = document.getElementById("myList").childNodes[0];
item.replaceChild(textnode, item.childNodes[0]);
}
</script>
- 咖啡
- 茶
- 牛奶
单击按钮以替换列表中的第一项
试试看
函数myFunction(){
var textnode=document.createTextNode(“水”);
var item=document.getElementById(“myList”).childNodes[0];
item.replaceChild(textnode,item.childNodes[0]);
}
1)childNodes
是有问题的,因为它不仅计算您视觉上看到的节点,还计算空白节点和注释节点。对于以下示例:
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
childNodes.length
将返回9!(5个空白节点(类型:TEXT_节点)、1个注释节点和3个元素节点)。这就是为什么节点元素有一个属性,您可以通过检查该属性来确定类型。但是您可能希望使用而不是childNodes
2) 最简单的解决方案有时是最好的。我会采取直截了当的方法:
document.querySelector("#myList li:first-of-type").innerHTML = "Water"
请参阅(查看控制台输出)
3) 不鼓励使用内联事件,最好通过addEventListener
将事件绑定到js中的节点
而不是
<button onclick="myFunction()">Try it</button>
试试看
使用
试试看
document.getElementById(“某些id”).addEventListener(myFunction);
4) 不管这个名字意味着什么,w3c学校并不隶属于w3c,而且,由于过去的许多负面经验,w3c学校不被视为Web开发信息的一个非常著名的来源。他们最近有所改进,但我仍然不会选择它作为我的主要信息来源。另请参见“不起作用”的确切含义是什么?你犯了什么错误?谢谢。你说的有道理,而且我认为它们包括回车和空格作为节点。
<button onclick="myFunction()">Try it</button>
<button id="some-id">Try it</button>
<script>
document.getElementById("some-id").addEventListener(myFunction);
<script>