未捕获类型错误:Failed to execute 'appendChild'on 'Node&

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. BUT when tested using nodetype it returns 1

本文关键字:appendChild Node on execute to 类型 错误 Failed      更新时间:2023-09-26

我在我的代码中得到这个错误。我试着加上"。nodeType"当抓取节点时,看看它是否是一个节点,当我在JS中添加"警报"时,我得到1。这意味着它肯定是一个节点,对吧?

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

无论如何,我还没有在那里,我只是试图在页面的一侧生成笑脸,通过附加一个子节点到<div>,这是页面的LHS,但它不会工作,我不知道为什么不。下面是我的代码:

<!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>

尝试在chrome中运行此命令会在第40行出现上述错误。

                theLeftSide.appendChild("img"); 

无论我把<script>放在程序的哪个位置,它都会这样做:/

我已经试了很长时间了,谁能告诉我?

Uncaught TypeError: Failed to execute 'appendChild' on 'Node':参数1不是'Node'类型。但是当使用nodetype测试时,它返回1

不,你传入的类型是string

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

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

theLeftSide.appendChild(img);

…因为您已经创建了元素并将其分配给一个名为img的变量。