我有一个表,当新用户活跃时动态添加行。该函数将添加一个显示用户名的新行和一个激活灯箱以显示更多信息的按钮。名称和按钮放在一个单元格中,但我想右对齐按钮并左对齐单元格中的名称。我找到这篇文章 Right align and left align text in same HTML table cell这显示了如何在 HTML 中使用 div,但我需要动态地执行此操作。有人猜吗?我尝试了以下代码,它有效,但没有证明我想要的名称和按钮的合理性。它只是将它们集中在单元格中。我将不胜感激任何帮助。
function addRow(tableID, user, phone, age, city, zipCode) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
tabbody=document.getElementsByTagName("tbody").item(2);
cell1 = document.createElement("TD"); //Create New Row
leftDiv = document.createElement("div"); //Create left div
leftDiv.id = "left"; //Assign div id
leftDiv.setAttribute("style", "float:left;width:50%;"); //Set div attributes
rightDiv = document.createElement("div"); //Create right div
rightDiv.id = "right"; //Assign div id
rightDiv.setAttribute("style", "float:right;width:50%;"); //Set div attributes
user_name = document.createTextNode(user + ' '); //Set user name
details_btn = document.createElement("button"); //Create details button
btn_txt = document.createTextNode("Details"); //Create button text
details_btn.appendChild(btn_txt); //Add "Details" to button text
details_btn.onclick = function(){moreInfo(user, phone, age, city, zipCode);}; //Assign button function
cell1.appendChild(leftDiv);
cell1.appendChild(user_name); //Add name to row
cell1.appendChild(rightDiv);
cell1.appendChild(details_btn); //Add button to row
row.appendChild(cell1); //Add row to table
tabbody.appendChild(row);
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
最佳答案
试试这个:
function creatediv() {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.style.width = 300;
newdiv.style.height = 300;
newdiv.style.position = "absolute";
newdiv.style.background = "#C0C0C0";
newdiv.innerHTML = "Dynamic Div";
document.body.appendChild(newdiv);
}
关于javascript - 动态添加div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428026/