简体   繁体   English

Javascript DOM-将表单元素添加到新创建的appendChild吗?

[英]Javascript DOM - add form element to newly created appendChild?

I have two functions to add and remove table rows that contain a form input element. 我有两个函数来添加和删除包含表单输入元素的表行。 They both work fine, but I have a problem in that I need to show a Remove button input only on subsequently created table rows. 它们都可以正常工作,但是我有一个问题,我只需要在随后创建的表行上显示“删除”按钮输入。 My two function are as as follows: 我的两个功能如下:

function addRow(table_id){
var clone;
var rows=document.getElementById(table_id).getElementsByTagName('tr');
var index=rows.length;
var tbo=document.getElementById(table_id).getElementsByTagName('tbody')[0];
clone=rows[index-1].cloneNode(true);
tbo.appendChild(clone);
}

function delRow(table_id,button){
var row = button.parentNode.parentNode;
var tbo = document.getElementById(table_id).getElementsByTagName('tbody')[0];   
tbo.removeChild(row);
}

and the html content is: 和html内容是:

<form>
<table id="mytab">
<tr>
<td>Upload File <input type="file" name="uploadfile[]" onchange="addRow('mytab')" /> <input name="del_row" type="button" value="Remove Row" onclick="delRow('mytab',this)"/></td>
</tr>
</table>
</form>

I am by no means a Javascript expert - more of a newbie - so I'm struggling to come up with a solution. 我绝不是Java语言专家,而是更多的新手,因此我一直在努力提出解决方案。

I'm assuming that you are trying to avoid having the remove button in the first row, but need it there now because you think that to get it in subsequent rows, you need to have it in the row that you are cloning. 我假设您正在尝试避免在第一行中使用“删除”按钮,但现在需要该按钮,因为您认为要在后续行中获取它,就需要在要克隆的行中使用它。 If, instead, you just insert new HTML for both the upload and delete button inputs in the addRow method you can avoid the clone entirely and it won't matter what your original row contains. 相反,如果仅在addRow方法中为上载和删除按钮输入插入新的HTML,则可以完全避免克隆,并且原始行包含的内容也没有关系。

function addRow(table_id){
   var table = document.getElementById(table_id);
   var row = table.insertRow(table.rows.length);
   var cell = row.insertCell(0);
   var template = table.rows[0].cells[0].innerHTML;
   cell.innerHTML = template + '<input type="button" value="Remove Row"'
                 + ' onclick="delRow(\'' + table_id + '\',this);" />'
}

This still uses the first row as the template, but you can remove the button from it as it is added by appending to the existing text. 它仍然使用第一行作为模板,但是您可以通过将按钮添加到现有文本中来删除按钮。

If you need to create this element 如果您需要创建此元素

<input name="del_row" type="button" value="Remove Row" onclick="delRow('mytab',this)"/>

everytime the addRow function is called, you can just do this inside addRow(); 每次调用addRow函数时,您都可以在addRow()内部执行此操作;

var input = document.createElement("input");
input.setAttribute("name", "del_row");
input.setAttribute("type", "button");
input.setAttribute("value", "Remove Row");
input.onclick = function() {
    delRow("+table_id+", this);
};

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

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