【问题标题】:Adding a second element while iteratively adding an element with Javascript?在使用 Javascript 迭代添加元素时添加第二个元素?
【发布时间】: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",但没有按钮。如何在我的迭代旁边添加/插入/附加一个附加元素?有没有比我目前提出的更有效的方法?

【问题讨论】:

标签: javascript html


【解决方案1】:

只需将 button 作为子元素附加到 li 元素即可。

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!"
  listButton.style.margin = '10px';
  listItem.textContent = obj[key];
  listItem.appendChild(listButton);

  container.appendChild(listItem);
}
&lt;ul id="container"&gt;&lt;/ul&gt;

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多