这是我的HTML:
<table id="ParamTbl">
<tbody>
<tr id="ParamRow">
<td><label for="paramname[]">Name: </label><input type="text" name="paramname[]" class="paramname"></td>
<td><label for="paramval[]">Value: </label><input type="text" name="paramval[]"></td>
<td><label for="paramtype[]">Type: </label><select name="paramtype[]">
<option selected="true">String</option>
<option>Double</option>
<option>Object</option>
</select></td>
<td><div id="clrList">X</div></td>
<td><div id="addrow">Add Param</div></td>
</tr>
</tbody>
</table>
这是我的jQuery:
function addParam(ParamName){
$('#ParamTbl').css('background-color','yellow');
var clone = $('#ParamTbl').closest("tr").clone();
clone.appendTo('#ParamTbl').find(":input").val(ParamName);
$('#ParamTbl').closest("td").remove();
}
css('background-color','yellow');
用于调试目的,我在那里也有一些alerts()
,该函数被称为ok,并且ParamName被传递给它。
所以,问题是:为什么不附加我的行?
答案 0 :(得分:2)
尝试更改:
var clone = $('#ParamTbl').closest("tr").clone();
为:
var clone = $('#ParamTbl').find("tr#ParamRow").clone();
因为closest()遍历DOM树中的祖先。
答案 1 :(得分:2)
http://api.jquery.com/closest/
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
请尝试find
:
var clone = $('#ParamTbl').find("tr:first").clone();
答案 2 :(得分:2)
完全重新设计
HTML
<table id="ParamTbl">
<tbody>
<tr>
<td><label for="paramname[]">Name: </label><input type="text" name="paramname[]" class="paramname"/></td>
<td><label for="paramval[]">Value: </label><input type="text" name="paramval[]"/></td>
<td><label for="paramtype[]">Type: </label><select name="paramtype[]">
<option selected="true">String</option>
<option>Double</option>
<option>Object</option>
</select></td>
<td><div class="clrList">X</div></td>
<td><div class="addrow">Add Param</div></td>
</tr>
</tbody>
</table>
JS
$(function(){
var $table = $('#ParamTbl');
$('#ParamTbl').on('click', '.addrow', function(){
$table.css('background-color','yellow');
var tr = $(this).closest('tr');
var clone = tr.clone();
clone.appendTo($table).find('input[name="paramval[]"]').val('');
$(this).remove();
})
$('#ParamTbl').on('click', '.clrList', function(){
$(this).closest('tr').remove()
})
});
演示:Fiddle