gpt4 book ai didi

JavaScript 网站错误 : Uncaught TypeError: Failed to execute 'appendChild' on 'Node'

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:18 26 4
gpt4 key购买 nike

嘿,我正在尝试仅使用 JavaScript 制作一个网站,但出现此错误:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'at html:12:9

这是我的 html 代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>

<script>
var divEl = document.createElement("div");
document.body.appendChild(divEl);
var ptag = document.createElement("p").setAttribute("id", "lol");
divEl.appendChild(ptag);

</script>

</body>
</html>

最佳答案

setAttribute 不返回节点,因此您的 ptag 变量被设置为 undefined

来自doc :

Adds a new attribute or changes the value of an existing attribute on the specified element. Returns undefined.

尝试在单独的语句中调用 setAttribute:

<script>
var divEl = document.createElement("div");
document.body.appendChild(divEl);
var ptag = document.createElement("p");
ptag.setAttribute("id", "lol");
divEl.appendChild(ptag);
</script>

JSBin:http://jsbin.com/wibeyewuqo/edit?html,output

关于JavaScript 网站错误 : Uncaught TypeError: Failed to execute 'appendChild' on 'Node' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41187937/

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