Uncaught TypeError:无法执行“节点”上的“appendChild”:参数1不是“节点”types。 但是当使用nodetypetesting时,它返回1

我在我的代码中得到这个错误。 我试图在抓取节点时添加“.nodeType”,看看它是否是一个节点,当我在JS中添加一个“alert”时,我得到1.所以这意味着它肯定是一个节点吧?

这个代码是用于匹配的游戏,我将文档分成两个(节点),并在左侧随机生成笑脸。 最后的游戏是将完全相同的面克隆到第二个节点上,即页面的RHS,然后删除一个。 然后,用户必须点击页面左侧的额外笑脸。

无论如何,我还没有在那里,我只是试图在页面的一侧生成表情符号,通过将一个子节点添加到该页面的LHS的<div> ,但它不会工作,我看不到为什么不。 这是我的代码:

 <!DOCTYPE HTML> <html> <head> <style> img {position:absolute;} /*here i tried to use 500px in the style rules for the div but the division was noticeably off centre, therefore, i used 50% instead*/ div {position:absolute; width:50%; height:50%} #rightSide {left:50%; border-left: 1px solid black} </style> </head> <body onload="generateFaces()"> <h1 id="TitleOfGame">Matching Game!</h1> <p id="Intructions">To play the game, find the extra smiley on the left hand side and click on it :)</p> <div id="leftSide"> <!--this div node will display all of the faces on the left side of the screen faces are dynamically added using javascript--> </div> <div id="rightSide"> <!--this div node will display all of the faces on the right side of the screen cloneNode(true) is used to copy the faces to the right side, and the last child of this branch is deleted, such that there are more faces on the left side. --> </div> </body> <script> var numberOfFaces=5; var theLeftSide = document.getElementById("leftSide"); var i=0; function generateFaces(){ while (i<numberOfFaces){ var random_top=((Math.random()*400)); var random_left=((Math.random()*400)); var random_top=Math.floor(random_top); var random_left=Math.floor(random_left); var img=document.createElement('img'); img.src="smile.png"; img.style.left=random_left; img.style.top=random_top; theLeftSide.appendChild("img"); i+=1; } } </script> </html> 

试图运行这个铬在第40行即上面的错误。

  theLeftSide.appendChild("img"); 

而且,无论在哪里,我都把<script>放在程序中:/

我一直在努力,谁能告诉我?

Uncaught TypeError:无法执行“节点”上的“appendChild”:参数1不是“节点”types。 但是当使用nodetypetesting时,它返回1

不,你传递的是stringtypes

 theLeftSide.appendChild("img"); // This is parameter 1 ^^^^^ 

appendChild需要一个节点,而不是一个string。 看你的代码,你所要做的就是删除引号:

 theLeftSide.appendChild(img); 

…因为您已经创build了该元素并将其分配给一个名为img的variables。