我有這個 JS 和 HTML 內容:
const parent = document.querySelector('#parent');
const choices = parent.dataset.choices.split(",")
const childTplt = document.querySelector('#children');
for (c of choices) {
let child = childTplt.content.cloneNode(true);
child.appendChild(document.createTextNode(c));
parent.appendChild(child);
}
<ul id="parent" data-choices="one,two,three">
</ul>
<template id="children">
<li> </li>
</template>
并在我的頁面上結束:
<ul id="parent" data-choices="one,two,three">
<li> </li>
one
<li> </li>
two
<li> </li>
three</ul>
為什么文本內容最終成為的兄弟<li>而不是實際的孩子(在<li></li>?
感謝您的輸入!
uj5u.com熱心網友回復:
.content模板元素的屬性是檔案片段;它是不是該<li>元素。在您的情況下,模板很簡單,因此您可以只參考片段的第一個子項:
let child = childTplt.content.firstElementChild.cloneNode(true);
uj5u.com熱心網友回復:
這對我有用
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
li.setAttribute("id", "element4");
ul.appendChild(li);
alert(li.id);
}
uj5u.com熱心網友回復:
在上面的回圈中,您要附加c(一、二、三),然后附加內部內容的克隆版本#children。
for (c of choices) {
let child = childTplt.content.cloneNode(true);
child.appendChild(document.createTextNode(c)); //will append 'one'
parent.appendChild(child); //will append <li></li>
}
你可以用這個回圈替換它,它會做你的目標:
for (c of choices) {
let li = document.createElement('li');
li.append(c);
parent.append(li);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/382341.html
標籤:javascript html dom 浏览器
