Javascript 在javascript中的表中动态添加/删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12206959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:24:39  来源:igfitidea点击:

Add/Remove rows dynamically in a table in javascript

javascripthtmlforms

提问by RobG

I want to add/remove rows in a table dynamically. I have javascript function to add and remove the rows. But, I want the delete button beside every single row so that I can delete a particular row.

我想动态添加/删除表中的行。我有 javascript 函数来添加和删除行。但是,我希望在每一行旁边都有一个删除按钮,以便我可以删除特定的行。

ANd I want to add a row only if the first row is completely filled.

并且我只想在第一行完全填满时添加一行。

function to remove row

删除行的函数

 function removeRowFromTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}

function to add rows:

添加行的函数:

function addRow(tableID) {

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "text";
            cell1.appendChild(element1);

            var cell2 = row.insertCell(1);
            var element2 = document.createElement("input");
            element2.type = "text";
            cell2.appendChild(element2);
        }

my table:

我的表:

<table id="tableId">
<tr><td>Host Name</td><td>Directory</td></tr>
<tr><td><input type="text"/></td><td><input type="text"/></td></tr>
<tr><td><input type="button" value="+" onclick="addRow(tableId)"/></td>
<td><input type="button" value="-" onclick="removeRowFromTable()"/></td></tr>
</table>

Any help is appreciated! Thanks in Advance!!!

任何帮助表示赞赏!提前致谢!!!

回答by RobG

If you put a delete button on each row, then:

如果在每一行上放置一个删除按钮,则:

<tr>
  <td><input type="button" value="Delete row" onclick="deleteRow(this)">
  <td><input type="text">
  <td><input type="text">
</tr>

And the deleteRow function can be:

而 deleteRow 函数可以是:

function deleteRow(el) {

  // while there are parents, keep going until reach TR 
  while (el.parentNode && el.tagName.toLowerCase() != 'tr') {
    el = el.parentNode;
  }

  // If el has a parentNode it must be a TR, so delete it
  // Don't delte if only 3 rows left in table
  if (el.parentNode && el.parentNode.rows.length > 3) {
    el.parentNode.removeChild(el);
  }
}

BTW, if all your rows have the same content, it will be much faster to add a row by cloning an existing row:

顺便说一句,如果您所有的行都具有相同的内容,那么通过克隆现有行来添加行会快得多:

function addRow(tableID) {
  var table = document.getElementById(tableID);

  if (!table) return;

  var newRow = table.rows[1].cloneNode(true);

  // Now get the inputs and modify their names 
  var inputs = newRow.getElementsByTagName('input');

  for (var i=0, iLen=inputs.length; i<iLen; i++) {
    // Update inputs[i]
  }

  // Add the new row to the tBody (required for IE)
  var tBody = table.tBodies[0];
  tBody.insertBefore(newRow, tBody.lastChild);
}

回答by 3coins

You can avoid a lot of cross browser headaches by using jquery. Here is a sample.

通过使用 jquery,您可以避免很多跨浏览器的麻烦。这是一个示例。

http://jsfiddle.net/piyushjain7/gKJEs/

http://jsfiddle.net/piyushjain7/gKJEs/

回答by Oriol

See http://jsfiddle.net/9gnAx/

http://jsfiddle.net/9gnAx/

HTML & JavaScript (body):

HTML 和 JavaScript(正文):

<table id="tableId">
    <tr>
        <th>Host Name</th>
        <th>Directory</th>
        <td><input class="add" type="button" value="+" /></td>
    </tr>
    <tr>
        <td></td><td></td>
        <td><input class="add" type="button" value="+" /></td>
    </tr>
</table>
<script type="text/javascript">
    (function(){
    var els=getElementsByClassName("add","tableId");
    for(var i=0;i<els.length;i++){
        els[i].onclick=addRow;
    }
    els[0].onclick();
    })();
</script>

CSS (head):

CSS(头):

.add,.del{
    width:25px;
}

JavaScript (head):

JavaScript(头部):

function getElementsByClassName(c,el){
    if(typeof el=='string'){el=document.getElementById(el);}
    if(!el){el=document;}
    if(el.getElementsByClassName){return el.getElementsByClassName(c);}
    var arr=[],
        allEls=el.getElementsByTagName('*');
    for(var i=0;i<allEls.length;i++){
        if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
    }
    return arr;
}
function killMe(el){
    return el.parentNode.removeChild(el);
}
function getParentByTagName(el,tag){
    tag=tag.toLowerCase();
    while(el.nodeName.toLowerCase()!=tag){
        el=el.parentNode;
    }
    return el;
}
function delRow(){
    killMe(getParentByTagName(this,'tr'));
}
function addRow() {
    var table = getParentByTagName(this,'table')
    var lastInputs=table.rows.length>2?
        table.rows[table.rows.length-2].getElementsByTagName('input'):[];
    for(var i=0;i<lastInputs.length-1;i++){
        if(lastInputs[i].value==''){return false;}
    }
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount-1);

    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.type = "text";
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement("input");
    element3.type = "button";
    element3.className="del";
    element3.value='-';
    element3.onclick=delRow;
    cell3.appendChild(element3);
}

Update:

更新:

RobG has made me realize that getParentByTagNamethrows an error if there isn't any parent with the nodeNamepassed.

RobG 让我意识到,getParentByTagName如果没有任何父级nodeName通过,则会引发错误。

If you want a more general getParentByTagName, which doesn't throw errors, you can use

如果你想要一个更通用的getParentByTagName,不会引发错误的,你可以使用

function getParentByTagName(el,tag){
    tag=tag.toLowerCase();
    while(el&&el.nodeName.toLowerCase()!=tag){
        el=el.parentNode;
    }
    return el||null;
}

And when you call the function you should check if the result is null.

当您调用该函数时,您应该检查结果是否为null.

Updated jsfiddle: http://jsfiddle.net/9gnAx/1/

更新 jsfiddle:http: //jsfiddle.net/9gnAx/1/

回答by aug

Javascript has this really useful function called deleteRowwhere if you know the index you are deleting from, you can simply input that number, and then it'll delete that specific row (index's starting at 0 - tbl.rows.length).

Javascript 有一个非常有用的函数,称为deleteRow,如果您知道要从中删除的索引,您只需输入该数字,然后它就会删除该特定行(索引从 0 开始 - tbl.rows.length)。

I also found a nice examplethat uses it in action. You can adjust it to fit your needs though (although his uses checkboxes which might be a lot cleaner than just making a button next to every single row). I don't encourage you to blatantly copy the code so if there is anything that confuses you, please let us know. Hope this helps.

我还发现了一个很好的例子,它在行动中使用它。您可以调整它以满足您的需要(尽管他使用复选框可能比在每一行旁边制作一个按钮要干净得多)。我不鼓励你公然复制代码,所以如果有任何让你困惑的地方,请告诉我们。希望这可以帮助。

EDIT: I didn't see you wanted to add rows after you found out the last row was completely filled. I'll update my answer when I figure that out. However, the basic idea of that is to check if the <td>tag has text in it (perhaps check if the text inside the tag isn't a blank or if there is a <td>tag at all and then if it isn't empty, make a new <tr>element else don't.

编辑:在您发现最后一行已完全填满后,我没有看到您想要添加行。当我弄清楚时,我会更新我的答案。但是,其基本思想是检查<td>标签中是否有文本(也许检查标签内的文本是否不是空白或根本没有<td>标签,然后如果它不是空的,则创建一个新<tr>元素否则不会。