使用jQuery向表格添加行

3

我正在尝试开发一个jQuery插件。这是我的第一个插件,我在初始阶段遇到了困难。

我需要做以下几件事:我需要从表格中找到“添加行”链接并绑定到单击事件。当单击链接时,它应该通过克隆现有的模板行来添加新行。初始时模板行是隐藏的。

以下是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);

5
嘿,听起来像是一个“请为我编写整个插件”的案例。 - John Green
我尝试过了,但在传递参数时卡住了。 - Ujjwal Manandhar
@Tomalak,从来没有听过jQuery作业lol - Naftali
5个回答

3

您需要使用.detach()方法从表格中分离出模板,并将其放置在一个工厂变量中,例如:

var factory = $('#template_row').detach();
factory.removeAttr('id'); // Suggestion for Tomalak

它将从表格中隐藏(实际上并没有)。下一步是绑定点击您的链接,并指定新的factory.clone项目所在的位置。例如:

$('button.new-link').click(function(){
  $('#data_table').append(factory.clone(true));
}); 

同时还要看看 .clone()插件编写


1
建议使用detach()函数,只需要从“factory variable”/模板中删除id属性即可。 - Tomalak

2
不需要插件,只需按照以下步骤操作:
$('#add_row').click(function(){
     var clone = $('#template_row').clone();
     clone.removeAttr('id');
     clone.appendTo('#data_table');
})

这是一个演示:http://jsfiddle.net/Jw5TF/

2
一行代码:$('#data_table').append( $('#template_row').clone().removeAttr('id') ); - Tomalak
@Tomalak,是的,这也是真的 :-P - Naftali
1
我通常不是一个代码高手,但这太诱人了。;) - Tomalak

2

从您当前的代码开始:

(function($) {
  $.extend($.fn, {
    editableGrid: function() {
      this.find("a.add_row").click(function () {
        var $table  = $(this).parent("table").find("table.data_table");
        var $newRow = $table.find("tr.template_row").clone();

        $newRow.removeClass("template_row"); // !!!
        $table.append($newRow);
        return false;
      });
    }
  });   
})(jQuery);

注解

  • 使用 CSS 类而不是 ID——只有这样才能在一页上拥有多个“可编辑网格”。
  • 在这里,使用 click() 没有比使用 bind() 更好的效果。
  • 您可以直接将函数作为参数传递 - 不需要单独定义它们。
  • 使用冗长的选择器(例如"a.add_row")可以提高可读性/清晰度,而不仅仅是使用".add_row"
  • 在外部函数中,this 指的是包含所有匹配元素的 jQuery 对象,因此 click() 在一步中绑定了所有匹配的元素。
  • 在内部函数中,this 指的是单个 DOM 元素(即被点击的链接),这里不是一个 jQuery 对象!
  • 别忘了从 click 函数返回 false,以防止浏览器默认行为。
  • 在变量前面加上 $ 是很有用的,用于表示它们包含一个 jQuery 对象。

谢谢您的描述 :) .. 它现在可以工作了,我正在扩展它以供我的使用.. - Ujjwal Manandhar
@Ujjwal 很高兴听到这个消息!还要看看 @DavidRodrigues 的答案,他提出的 detach() 建议是进一步改进的好方法。 - Tomalak

1
$.fn.myTableTingPlugin = function() {
  var self = this;

  $(self).find(".template_row").hide(); // or use css class
  $(this).find(".add_row").click(function() { 
     // shuld probebly not use ids if its a plugin 
     // so i use a class here

     var newRow =  $(self).find(".template_row").clone();
     $(self).find(".data_table").append(newRow);
  });
}; 

1
首先,不要使用id,类更好。双引号也更好。
<table class="extendableTable">
    <tr>
        <td><a href="#" class="extendLink">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>

插件的源代码:

(function($) {
    $.fn.extendableTable = function(options){
        var table = this;
        this.find('.extendLink').click(function(){
            table.find('.dataTable .templateRow:first').clone().appendTo(table.find('.dataTable'));
            return false;
        });
    }
})(jQuery);

然后你可以这样使用插件:

$('.extendableTable').extendableTable();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接