简体   繁体   English

如何使用 appendChild 附加多个元素

[英]How to append more than one element using appendChild

I have one cell (columns), in which I want to add two buttons.我有一个单元格(列),我想在其中添加两个按钮。 This is what I created:这是我创建的:

var editbtn = document.createElement('button');
editbtn.type= "button";
editbtn.className= "editbtn";
editbtn.id= "edit-button-"+(i+1);
editbtn.innerHTML= "Edit";
editbtn.onclick = editRow.bind(this, i + 1); 

var savebtn = document.createElement('button');      
savebtn.type= "button";
savebtn.className= "savebtn";
savebtn.id= "save-button-"+(i+1);
savebtn.innerHTML= "Save";
savebtn.onclick = saveRow.bind(this, i + 1);

cell3.appendChild(editbtn); 
cell3.appendChild(savebtn); 

However, only the savebtn appears.但是,只有savebtn出现。 How to append two buttons or more in the same column?如何在同一列中附加两个或更多按钮?

You can easily do that with an array and a for loop:您可以使用数组和 for 循环轻松做到这一点:

var names = ['edit', 'save'];
var editRows = [editRow, saveRow];

for ( var i = 0; i < names.length; i++ )
{
    var btn       = document.createElement('button');
    btn.type      = "button";
    btn.className = names[i] + "btn";
    btn.id        = names[i] + "-button-" + (i+1);
    btn.innerHTML = names[i];
    btn.onclick   = editRows[i].(this, i + 1);

    cell3.appendChild( editbtn );
}

You can add as many button as you want then just updating names and editRows accordingly, no need to touch the for loop.您可以添加任意数量的按钮,然后相应地更新nameseditRows ,无需触摸for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM