Java脚本:在表中动态添加文本字段和按钮

时间:2015-06-12 13:37:30

标签: javascript

我有一个按钮以及一个表格行。当我点击按钮时,应该在表格中添加新行,按钮应该出现在新添加的行中。请查看图片enter image description here

2 个答案:

答案 0 :(得分:0)

以下是使用按钮添加新行的快速解决方案,这些按钮也会添加新行。

您没有添加任何代码,但这可行。

https://jsfiddle.net/scheda/Lhsvmqoy/

var b = document.querySelector('.clicky')
var table = document.querySelector('table');
var insert_this = '<tr><td><input type="text" placeholder="Look ma!"/><button class="clicky">Add more stuff</button></td></tr>';

document.querySelector('body').addEventListener('click', function(e) {
    if (e.target.className === 'clicky') {
        table.innerHTML += insert_this;
    }
});

答案 1 :(得分:0)

这应该按照您的预期运作:

<!DOCTYPE html>
<head>
    <style>
        td,table{border:solid 1px;}
    </style>
    <title>Table sample </title>    
</head> 
<body>
<table id="myTable">
    <tr>
        <td>Row 1</td><td></td>
    </tr>
    <tr>
        <td>Row 2</td><td><button  id="newRow">New Row (original button)</button></td>
    </tr>
</table>        
</body>

<script>
    function addRow() {
    // Get a reference to the table
    var tableRef = document.getElementById('myTable');

   // Insert a row in the table at the end 
   var newRow   = tableRef.insertRow(tableRef.rows.length);

   // Insert a cell in the row at index 0
   var newCell  = newRow.insertCell(0);
   newCell.innerHTML="Row " + tableRef.rows.length;
   var newCell  = newRow.insertCell(1);

   // Append button node to the cell
   var newButton  = document.getElementById('newRow');  
   newCell.appendChild(newButton);
}

function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    }else {
        elem.attachEvent("on" + event, function() {
        // set the this pointer same as addEventListener when fn is called
             return(fn.call(elem, window.event));   
        });
    }
}
var mybutton = document.getElementById("newRow");
addEvent(mybutton,"click",addRow);
</script>
</html>

<强>来源/现金: addEventListener函数: adding event listener cross browser

添加行功能(已修改): https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow