在构造函数中动态地将子项 div 附加到其父项

appending child div to its parent dynamically in the constructor

我在使用 appendchild() 在 div 中附加 div 时遇到问题。如果可能的话,我想避免使用 jquery.I 对父子 divs 使用构造函数。

<script>

    var loopi = 0;


    function codeDiv(){
        codeDiv1 = document.createElement("div");
        codeDiv1.style.height  = "100px";
        codeDiv1.style.width = "200px";
        codeDiv1.style.border = "thick solid black";

    }

    function functionObject(){
        var functionDivObject = document.createElement("div");
        functionDivObject.style.width = "500px";
        functionDivObject.style.height = "500px";
        functionDivObject.style.border = "thick solid black";
        document.body.appendChild(functionDivObject);
        var codeDiv1 = new codeDiv();
        functionDivObject.appendChild(codeDiv1);  //I am having the problem here
        functionDivObject.id = "functionDiv"+loopi;
        loopi++;
    }
    loopi = 0;


    var temp = new functionObject();

</script>

您的浏览器控制台应该有类似 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. 的错误,因为 appendChild() 方法需要 dom 元素引用作为其参数。

在你的情况下,你正在向它传递一个 codeDiv 实例。

您需要 return 来自 codeDiv

的新 div
function codeDiv() {
    var codeDiv1 = document.createElement("div");
    codeDiv1.style.height = "100px";
    codeDiv1.style.width = "200px";
    codeDiv1.style.border = "thick solid black";
    return codeDiv1;

}

演示:Fiddle

function codeDiv() {
    var codeDiv1 = document.createElement("div");
    codeDiv1.style.height = "100px";
    codeDiv1.style.width = "200px";
    codeDiv1.style.border = "thick solid black";
    return codeDiv1;

}

   function functionObject(){
        var functionDivObject = document.createElement("div");
        functionDivObject.style.width = "500px";
        functionDivObject.style.height = "500px";
        functionDivObject.style.border = "thick solid black";
        document.body.appendChild(functionDivObject);
        var codeDiv1 = codeDiv();  // call function which is returning div node
        functionDivObject.appendChild(codeDiv1);  //I am having the problem here
        functionDivObject.id = "functionDiv"+loopi;
        loopi++;
    }