【发布时间】:2018-12-06 03:49:01
【问题描述】:
我有一个对象,我想使用 JS 迭代地添加到 HTML 中。我想在每个对象的右侧添加一个按钮。
说,我的对象看起来像{"one": "One", "two": "Two", "three": "Three"}
最终结果应该是这样的:
- One [Click Me]
- Two [Click Me]
- Three [Click Me]
- etc...
HTML:
<ul id="container"></ul>
JS:
const container = document.getElementById("container")
const obj = {"one": "One", "two": "Two", "three": "Three"}
for(let key in obj) {
const listItem = document.createElement("li")
const listButton = document.createElement("button")
listButton.textContent = "Click me!"
listItem.textContent = obj[key]
// Unsure how to add the button
// Tried:
//
// const tempButton = document.createElement('button');
// tempButton.style.backgroundColor = "red"
// listItem.insertAdjacentElement('afterend', tempButton)
//
// also tried:
//
// listItem.insertAdjacentElement('afterend', '<div>Hello</div>')
container.appendChild(listItem)
}
我按预期看到了"One" "Two" "Three",但没有按钮。如何在我的迭代旁边添加/插入/附加一个附加元素?有没有比我目前提出的更有效的方法?
【问题讨论】:
-
查看这个答案,看看它是否有帮助。 stackoverflow.com/questions/2439642/…
标签: javascript html