AppendChild()不是一个javascript函数

AppendChild() is not a function javascript

本文关键字:一个 javascript 函数 AppendChild      更新时间:2023-09-26

这是我的javascript

<head runat="server">
    <script type="text/javascript" language="javascript">
        function createQuestionPanel() {
            var element = document.createElement("Input");
            element.setAttribute("type", "button");
            element.setAttribute("value", "button");
            element.setAttribute("name", "button");

            var div = '<div>top div</div>';
            div[0].appendChild(element);
        }
        function formvalidate() {
        }
    </script>
</head>
<body onload="createQuestionPanel()">
</body>
</html>

抛出错误"AppendChild不是一个函数"。我试图寻找解决办法。有人建议在

的位置

div.appendChild(元素);

这个应该张贴

div [0] .appendChild(元素);

它没有改变错误。请建议

您的div变量是一个字符串,而不是DOM元素对象:

var div = '<div>top div</div>';

字符串没有appendChild方法。不创建原始HTML字符串,而是将div创建为DOM元素并附加文本节点,然后附加输入元素:

var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));
div.appendChild(element);
 function createQuestionPanel() {
        var element = document.createElement("Input");
        element.setAttribute("type", "button");
        element.setAttribute("value", "button");
        element.setAttribute("name", "button");

        var div = document.createElement("div"); <------- Create DIv Node
        div.appendChild(element);<--------------------
        document.body.appendChild(div) <------------- Then append it to body
    }
    function formvalidate() {
    }

在此

var div = '<div>top div</div>';

"div"不是一个DOM对象,只是一个字符串,并且string没有string. appendchild .

这里有一些参考可以帮助你使用appendChild方法:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>

直接修改

var div = '<div>top div</div>'; // you just created a text string

var div = document.createElement("div"); // we want a DIV element instead
div.innerHTML = "top div";

尝试如下:

var div = document.createElement("div");
div.innerHTML = "topdiv";
div.appendChild(element);
document.body.appendChild(div);

我只使用$(".ClassName")[0].appendChild(div);$("#IdName")[0].appendChild(div); x)