【发布时间】:2019-04-29 06:44:12
【问题描述】:
我用javascript成功创建了这个模板:
我在 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 标签,但我找不到任何说我不能的东西。
更新
发生这种情况:
当我这样做时:
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>。
【问题讨论】:
-
您的代码应该可以工作。要尝试的一件事是让您的异步函数实际返回节点,并让您的
then函数接受节点作为参数。最好的办法是附加一个调试器并逐步执行代码。 -
好的...看看我的更新,这对你有意义吗?
-
我尝试从
async函数传递填充的template,但结果仍然相同 -
看看我的回答。如果克隆整个模板有效,那么只需遍历其子模板并克隆每个模板。
标签: javascript html cordova dom nodes