方法通过innerHTML添加元素

atmip9wb  于 2022-11-27  发布在  其他
关注(0)|答案(2)|浏览(224)
const myElement = document.createElement("div");
let selectItems = data.map((select, i) => (
    `<div class="select">
        <div aria-required="true" class="selectBtn" data-type="">${select.placeholder}</div>    
            <div class="selectDropdown">${select.option.map(el =>
                    `<div class="option" data-type="firstOption">${el}</div>`
            ).join('')}
        </div>
    </div>`)
)

const eles = document.getElementsByClassName("select");
for (let i = 0; i < eles.length; i++) {
    myElement.innerHTML = selectItems[i]; ///loop
    eles[i].appendChild(myElement.cloneNode(true));
}

我试图通过循环添加元素,但出现了无限循环

e5nqia27

e5nqia271#

您正在尝试访问selectedItems数组的无效索引。应在将此更新的元素追加到dom之后,将所有项一起追加到myElement。
我直接附加到正文,但您可以更改它。

const myElement = document.createElement("div");
let selectItems = data.map((select, i) => (
    `<div class="select">
        <div aria-required="true" class="selectBtn" data-type="">${select.placeholder}</div>    
            <div class="selectDropdown">${select.option.map(el =>
                    `<div class="option" data-type="firstOption">${el}</div>`
            ).join('')}
        </div>
    </div>`)
)

for (let i = 0; i < selectItems.length; i++) {
    myElement.innerHTML += selectItems[i];
}

document.body.appendChild(myElement);
vi4fp9gy

vi4fp9gy2#

你可以用JavaScript动态地创建你的HTML,结构化的方式如下。这对你将来有帮助。另外,你必须把你的顶层元素myElement附加到现有的HTML文档中的某个地方,就像这里我把它附加到body中一样。

const myElement = document.createElement("div");
let data = [{
  option: [0, 1, 2, 3],
  placeholder: "X"
}, {
  option: [0, 1, 2, 3],
  placeholder: "Y"
}];
data.map((select, i) => {
  const selectEl = document.createElement("div");
  selectEl.className = "select";
  const selectBtn = document.createElement("div");
  selectBtn.innerHTML = select.placeholder;
  selectBtn.className = "selectBtn";
  selectBtn["aria-required"] = true;
  selectBtn["data-type"] = "";
  selectEl.appendChild(selectBtn);
  const selectDropdown = document.createElement("div");
  selectDropdown.className = "selectDropdown";
  select.option.map(x => {
    const optionDiv = document.createElement("div");
    optionDiv.className = "option";
    optionDiv["data-type"] = "firstOption";
    optionDiv.innerHTML = x;
    selectDropdown.appendChild(optionDiv);
  });
  selectEl.appendChild(selectDropdown);
  myElement.appendChild(selectEl);
})

document.body.appendChild(myElement);

相关问题