为什么向appendChild传入匿名函数时运行结果不符合预期?
问题原因
Node.appendChild() 仅接收DOM节点类型的参数,你在Option1里直接把匿名函数本身传进去了,没有执行这个函数,自然拿不到它返回的DOM节点,就会报类型错误:
Uncaught TypeError: Node.appendChild: Argument 1 does not implement interface Node.
写法差异
三种写法的核心区别就是传给appendChild的参数类型:
- Option1:传入的是未执行的函数对象,不符合要求,报错。如果要沿用匿名函数的写法,改成立即执行函数即可,修改后代码如下:
// 修正后的Option1 function appendThis() { var parent = document.getElementById("parent"); // 匿名函数外增加括号包裹,末尾加()表示立即执行,传入的就是返回的div节点 parent.appendChild((function () { var child = document.createElement("div"); child.classList.add("child"); child.classList.add("red"); child.innerHTML = "appendThis()"; return child; })()); }
- Option2:直接传入创建完成的DOM节点,符合参数要求,运行正常。
- Option3:传入
createChild()的执行结果,也就是函数返回的DOM节点,符合参数要求,运行正常。
完整可运行示例代码
JS代码
// 修正后的Option1 function appendThis() { var parent = document.getElementById("parent"); parent.appendChild((function () { var child = document.createElement("div"); child.classList.add("child"); child.classList.add("red"); child.innerHTML = "appendThis()"; return child; })()); } // Option 2 function appendThat() { var parent = document.getElementById("parent"); var child = document.createElement("div"); child.classList.add("child"); child.classList.add("green"); child.innerHTML = "appendThat()"; parent.appendChild(child); } // Option 3 function createChild() { var child = document.createElement("div"); child.classList.add("child"); child.classList.add("yellow"); child.innerHTML = "createChild()/appendThese()"; return child; } function appendThese() { var parent = document.getElementById("parent"); parent.appendChild(createChild()); }
CSS代码
main{ height: 98vh; width: 98vw; display: flex; flex-direction: column; align-items: center; justify-content: center; } button{ height: 50px; width: 200px; } hr{ width: 200px; } .parent { height: 100%; width: 100%; } .child{ height: 30px; width: 200px; text-align: center; } .red { background-color: red; } .green { background-color: green; } .yellow { background-color: yellow; }
HTML代码
<body> <main> <div id="parent"></div> <hr> <button class="red" onclick="appendThis();">AppendThis</button> <button class="green" onclick="appendThat();">AppendThat</button> <button class="yellow" onclick="appendThese();">AppendThese</button> </main> </body>
内容的提问来源于stack exchange,提问作者alxl86
相关产品推荐
相关产品推荐

