Не могу клонировать <template>для добавления к <div> - PullRequest
0 голосов
/ 27 ноября 2018

Я успешно создаю этот шаблон с помощью JavaScript:

enter image description here

Я создаю шаблон в функции async:

this.createBoxes = async function() {
    var row_counter = 0;
    for (var i = 1; i < this.fake_data.length + 1; i++) {

        var item_box = document.createElement("div");
        item_box.style.flex = "0.5";
        item_box.style.backgroundColor = "white";
        item_box.style.display = "flex";
        item_box.style.flexDirection = "column";
        item_box.style.justifyContent = "flex-end";
        item_box.id = "item_box_"+i;

        var item_name = document.createElement("h3");
        item_name.style.flex = "0.2";
        item_name.style.backgroundColor = "orange";
        item_name.style.alignSelf = "center";
        item_name.innerText = this.fake_data[i - 1].name;
        item_name.id = "item_name_"+i;

        item_box.appendChild(item_name);

        this_row = document.getElementsByClassName("row")[row_counter];
        this_row.appendChild(item_box);

        if(i % 2 == 0) {
            var pool = document.getElementById("pool");
            var inner_row = document.createElement("div");
            inner_row.style.display = "flex";
            inner_row.style.flexDirection = "row";
            inner_row.style.flex = "0.5";
            inner_row.style.justifyContent = "space-around";
            inner_row.style.alignItems = "center";
            inner_row.style.backgroundColor = "green";
            inner_row.className = "row";

            pool.appendChild(inner_row);

            row_counter++;
        }
        else if(i == this.fake_data.length) {
            return;
        }
    }
}

Затем я делаю это:

    this.createBoxes().then(function() {
        var template = document.querySelector('#pool');
        var clone = template.content.cloneNode(true);
        document.querySelector(".app").appendChild(clone);
    })

Но, как вы можете видеть из моего скриншота, .app пуст.Что я делаю неправильно?Я использую Cordova и предполагаю, что он может использовать тег template, но я не смог найти ничего, что бы я не мог сказать.

ОБНОВЛЕНИЕ

Это происходит:

enter image description here

Когда я делаю это:

    this.createBoxes().then(function() {
        var template = document.querySelector('#pool');
        var clone = template.cloneNode(true);
        document.querySelector(".app").appendChild(clone);
    });

Использование template.cloneNode успешно перемещает <template> но это явно не то, что я хочу, я хочу получить содержимое <template> и переместить его в контейнер .app, а не весь <template>.

Ответы [ 2 ]

0 голосов
/ 27 ноября 2018

Я добавил контейнер в шаблон программно:

    var pool = document.getElementById("pool");

    var container = document.createElement("div");
    container.style.flex = "1";
    container.style.backgroundColor = "white";
    container.style.display = "flex";
    container.style.flexDirection = "column";
    container.id = "container";

    var row = document.createElement("div");
    row.style.display = "flex";
    row.style.flexDirection = "row";
    row.style.flex = "0.5";
    row.style.justifyContent = "space-around";
    row.style.alignItems = "center";
    row.style.backgroundColor = "green";
    row.className = "row";

    container.appendChild(row);
    pool.appendChild(container); 

Затем, вместо того, чтобы добавить свое содержимое в #pool <template>, я добавил его в #container, а затем сохранил #container узел в переменной, а затем импортировал его в .app:

var container_in_temp = document.querySelector('#pool>#container');
var targetContainer = document.querySelector('.app');
targetContainer.appendChild(document.importNode(container_in_temp, true));

Таким образом, он выглядит примерно так, с контейнером в .app, что на самом деле является предпочтительной структурой :).

enter image description here

0 голосов
/ 27 ноября 2018

Что ж, если клонирование самого узла работает, то ответ довольно прост - просто клонируйте / добавьте дочерние элементы шаблона:

this.createBoxes().then(function() {
    let template = document.querySelector('#pool');
    let app = document.querySelector(".app");
    for(let child of template.childNodes) {
        let clone = child.cloneNode(true);
        app.appendChild(clone);
    }
});

Обратите внимание, что я не тестировал этот код - вам может понадобитьсяпри необходимости отладить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...