无法将元素附加到div

时间:2015-07-13 22:14:20

标签: javascript html append

我的Javascript旨在执行以下操作。

我有一个带有6个子节点的父div。我用JS创建了3个div,然后将它们添加到父级中。然后我将原始的6个子节点插入到我刚创建的3个div中并附加到原始父节点。这3个div是最初的6个元素的兄弟姐妹,现在是他们的父母。

这几乎可行。但是原来的两个孩子并没有附加到中间div,正如我在Javascript中所预期的那样。我不知道自己做错了什么。下面是Javascript,这里是正在执行脚本的网页的链接。

http://digitalenamel.com/espresso-event-schedule/

setTimeout( function() {
    try{
        var calendar = document.getElementById('calendar');
        var calendarChildren = calendar.children;
        console.log("How many children does #calendar have? " + calendarChildren.length);
        var calendarHeaders = document.getElementsByClassName('fc-header');  
        var calendarBodies = document.getElementsByClassName('fc-content');
        var containerForCalendars1 = document.createElement("div");
        var containerForCalendars2 = document.createElement("div");
        var containerForCalendars3 = document.createElement("div");
        calendar.appendChild(containerForCalendars1);
        calendar.appendChild(containerForCalendars2);
        calendar.appendChild(containerForCalendars3);
        containerForCalendars1.appendChild(calendarHeaders[0]); 
        containerForCalendars1.appendChild(calendarBodies[0]);
        containerForCalendars2.appendChild(calendarHeaders[1]);
        containerForCalendars2.appendChild(calendarBodies[1]);
        containerForCalendars3.appendChild(calendarHeaders[2]);
        containerForCalendars3.appendChild(calendarBodies[2]);
        console.log("How many elements with the class of fc-header are inside the calendarHeaders array? " + calendarHeaders.length);
        console.log("How many elements with the class of fc-content are inside the calendarBodies array? " + calendarHeaders.length);
    }catch(err){
        console.log("There was a general error with JS for calendar.");
    }
}, 8000);

编辑:http://jsfiddle.net/xe1ssxeu/再现错误

1 个答案:

答案 0 :(得分:1)

使用您更新的问题,我尝试过了。正如我所说,我已经避开了你的方法,它有点过分了。你在JSFiddle中启用了jQuery,所以我使用它。

如你所说,你正在学习我已经包含了一些可以解释发生了什么的评论。

// Set this jQuery to run once the page is ready.
$('document').ready(function() {
    // Create a list of all the headers & all the contents
    var headers = $('.fc-header');
    var contents = $('.fc-content');

    // Cycle through the headers & contents (assuming they're equal in length)
    for(i=0; i<headers.length; i++) {

        // Add a div to calendar with an id of the for iterator so we can 
        // access it.
        $('#calendar').append('<div id="' + i + '"></div>');

        // Access that div using the id we added, then append the i'th header
        // and the i'th content.
        $('#' + i).append(headers[i]);
        $('#' + i).append(contents[i]);

        // Remove the id as we don't need it later.
        $('#' + i).removeAttr('id');
    }
})

JSFiddle