gpt4 book ai didi

javascript - 如何在没有第二个参数的情况下使用 insertBefore()?

转载 作者:行者123 更新时间:2023-11-29 17:45:18 26 4
gpt4 key购买 nike

this示例说明 insertBefore() 方法的第二个参数是可选的:

The child node you want to insert the new node before. When not specified, the insertBefore method will insert the newnode at the end.

我的代码:

let li = document.createElement('LI');
li.appendChild(document.createTextNode("Water"));
let list = document.getElementById('list');
list.insertBefore(li);
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

但是当我尝试使用带有一个参数的 insertBefore 时出现错误:

Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present.

但是这段代码可以正常工作:

list.insertBefore(li, list.childNodes[0])

最佳答案

In this example says that second parameter for insertBefore() method is optional:

这是不正确的,请参阅 MDNthe spec (尽管坦率地说,当前规范比 the old one 更难遵循)。 (不幸的是,准确性和完整性是 w3schools 的持续问题,强烈建议改用 MDN。)您可以使用 null 作为第二个参数,但您必须提供它:

let li = document.createElement('LI');
li.appendChild(document.createTextNode("Water"));
let list = document.getElementById('list');
list.insertBefore(li, null);
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

关于javascript - 如何在没有第二个参数的情况下使用 insertBefore()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50250214/

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