我無法弄清楚如何將陣列中的值添加為 div 的 .textContent 。
我想要發生的是,如果我收到一個陣列(主題),我希望將陣列的內容設定為 元素的 .textContent。
我覺得這段代碼是正確的,但似乎不起作用。有任何想法嗎?
const Tabs = (topics) => {
const tabsTopics = document.createElement("div");
const tabsOne = document.createElement("div");
const tabsTwo = document.createElement("div");
const tabsThree = document.createElement("div");
tabsTopics.classList.add("topics");
tabsOne.classList.add("tab");
tabsTwo.classList.add("tab");
tabsThree.classList.add("tab");
tabsTopics.appendChild(tabsOne);
tabsTopics.appendChild(tabsTwo);
tabsTopics.appendChild(tabsThree);
document.querySelectorAll(".tab").forEach((el, i) => {
el.textContent = topics[i];
});
return tabsTopics;
}
const topics = ['1', '2', '3'];
document.getElementById('container').appendChild(Tabs(topics));
<div id="container"></div>
uj5u.com熱心網友回復:
tabsTopics尚未插入 DOM,因此document.querySelectorAll(".tab")將找不到其子項。
你應該做
tabsTopics.querySelectorAll(".tab").forEach((el, i) => {
el.textContent = topics[i];
});
反而。
const Tabs = (topics) => {
const tabsTopics = document.createElement("div");
const tabsOne = document.createElement("div");
const tabsTwo = document.createElement("div");
const tabsThree = document.createElement("div");
tabsTopics.classList.add("topics");
tabsOne.classList.add("tab");
tabsTwo.classList.add("tab");
tabsThree.classList.add("tab");
tabsTopics.appendChild(tabsOne);
tabsTopics.appendChild(tabsTwo);
tabsTopics.appendChild(tabsThree);
tabsTopics.querySelectorAll(".tab").forEach((el, i) => {
el.textContent = topics[i];
});
return tabsTopics;
}
const topics = ['1', '2', '3'];
document.getElementById('container').appendChild(Tabs(topics));
<div id="container"></div>
uj5u.com熱心網友回復:
更短的方法...
const Tabs = (topics) =>
{
const tabsTopics = document.createElement('div')
for (topic in topics)
tabsTopics.appendChild(
Object.assign(
document.createElement('div')
, { className:'tab', textContent: topic }
)
);
return tabsTopics;
}
const topics = ['1', '2', '3']
document.getElementById('container').appendChild(Tabs(topics));
.tab {
color : blue;
}
<div id="container"></div>
uj5u.com熱心網友回復:
當您的元素仍在記憶體中時,您無法查詢Selector/All ,只有在將它們附加到 DOM 之后。
這是一個建議/重拍:
// DOM utility functions:
const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Task:
const createTabs = (topics) => {
// Create wrapper
const EL_topics = ELNew("div", {className: "topics"});
// Iterate topics and create tabs
topics.forEach(topic => {
EL_topics.append(ELNew("div", {className: "tab", textContent:topic}));
});
// Append wrapper to container
EL("#container").append(EL_topics);
};
createTabs(["1", "2", "3"]);
<div id="container"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426147.html
標籤:javascript 数组 dom
