如何在纯 javascript 中一次创建多个按钮?

How to create several buttons at once in pure javascript?

CSS 网格布局:

.wrapper {
    display: grid;
    grid-template-areas: "btn1 btn2 btn3 btn4";
    grid-template-columns: repeat(4, 1fr);
}
#btn {grid-area: "btn1"}
#btn2 {grid-area: "btn2"}
#btn3 {grid-area: "btn3"}
#btn4 {grid-area: "btn4"}

由 div 和按钮创建:

const div = document.createElement("div");
div.classList.add("wrapper");
const body = document.body;
body.appendChild(div);
const button = document.createElement("button");
button.textContent = "Click1";
button.setAttribute("id", "btn");

接下来,我想在第一个按钮的基础上再创建三个按钮,并将它们粘贴到各自的区域。如果你愚蠢地描述每个动作:

const b2= button.cloneNode(true);
const b3= button.cloneNode(true);
const b4= button.cloneNode(true);
b2.setAttribute('id', 'btn2');
b3.setAttribute('id', 'btn3');
b4.setAttribute('id', 'btn4');
b2.textContent = "Click"+2;
b3.textContent = "Click"+3;
b4.textContent = "Click"+4;
div.appendChild(button);
div.appendChild(b2);
div.appendChild(b3); 
div.appendChild(b4);

如何做到最好?像这样的东西(不起作用):

let b2, b3, b4;
let arr = [b2,b3,b4]
 let i=2;
     while(i<5){
     for(let j=0; j<arr.length; j++){
     arr[j].setAttribute('id', 'btn'+ i);
     arr[j].textContent= "Click"+i;
div.appendChild(arr[j])
      } i++}

使用insertAdjacentHTML 可以简化任务。在此代码段中,div 和按钮是一次性创建的:

let buttons = [...Array(4)].map( (_, i) => 
  `<button id=btn${i + 1}>Click ${i + 1}</button>`);
document.body.insertAdjacentHTML(
  `beforeend`, `<div id="buttons">${
    buttons.join(``)}</div>`);
button {margin-right: 3px;}
#buttons {
  border: 1px solid #ddd;
  padding: 0.3rem;
  width: 50vw;
  text-align: center;
}

不需要重复,或者 clone,只需一个 for 循环。这里使用 documentFragment 来避免多次插入 DOM.

const div = document.createElement('div');
div.classList.add('wrapper');

document.body.appendChild(div);

const buttonCount = 4
const buttonFragment = document.createDocumentFragment();
for (let i = 1; i <= buttonCount; i++) {
    const button = document.createElement('button');
    button.textContent = `Click${i}`;
    button.id = `btn${i}`;
    buttonFragment.append(button);
}

div.append(buttonFragment);
.wrapper {display: grid; grid-template-areas: "btn1 btn2 btn3 btn4"; grid-template-columns: repeat(4, 1fr);}

#btn1 {grid-area: "btn1"; background-color: pink;}
#btn2 {grid-area: "btn2"; background-color: aquamarine;}
#btn3 {grid-area: "btn3"; background-color: gray;}
#btn4 {grid-area: "btn4"; background-color: salmon;}