我正在尝试为 jQuery 开发一个插件。这是我的第一个插件,我还停留在初始阶段。
我需要做以下事情:我需要从表中找到“添加行”链接并绑定(bind)到点击事件。单击链接时,它应该通过克隆现有模板行来添加新行。最初模板行是隐藏的。
以下是 HTML。
<table id='grid1'>
<tr>
<td><a href='#' id='add_row'>Add New Row</a></td>
</tr>
<tr>
<td>
<table id='data_table'>
<tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
<tr><td>Data1</td><td>Data2</td><td>Col3</td></tr>
<tr id='template_row'>
<td><input type='text' /></td>
<td><input type='text' /></td>
<td><input type='text' /></td>
</tr>
</table>
</td>
</tr>
</table>
到目前为止我的 jQuery:
(function($) {
$.extend($.fn, {
editableGrid: function() {
function addRow() {
//code to clone here but i need the instance of main table here ie grid1
}
this.find('#add_row').bind("click",addRow);
}
});
})(jQuery);
最佳答案
您需要 .detach()表中的模板并将其放在工厂变量上,例如:
var factory = $('#template_row').detach();
factory.removeAttr('id'); // Suggestion for Tomalak
它将隐藏(不是真的)从表中。下一步是绑定(bind)单击您的链接并在此处指定将转到新的 factory.clone 项目。喜欢:
$('button.new-link').click(function(){
$('#data_table').append(factory.clone(true));
});
也看看 .clone()和 plugin authoring
关于javascript - 使用 jQuery 向表中添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6067758/