0

我正在使用克隆将一行动态插入到带有 JQuery 的表中。

$('#Clone').click(function() {

    //put jquery this context into a var
    var $btn = $(this).parent();

    //use .closest() to navigate from the buttno to the closest row and clone it
    //use clone(true) to pass events to cloned item

    var $clonedRow = $btn.closest('tr').clone(true).insertAfter($btn);  

});

最终用户将控制新行的插入。我需要将新行数限制为 5。有没有办法使用 cookie 或其他方法(数组)来做到这一点。我可以有多个具有自己唯一 ID 的表,因此它需要与页面上的多个表一起使用。

希望你能帮忙。

4

5 回答 5

1

变量呢?

function addClick(identifier, max){
  var i = 0;
  $(identifier).click(function() {
    if (i < max){
       //add row
       i++;
    } 
  }
}
addClick("#Clone", 5);

或者,您也可以在用户添加的类上设置不同的类,然后在 add 函数中计算它们。

于 2010-02-02T21:20:40.237 回答
0

您可以只计算返回的元素数量。

function countRows() {
  return $("#table-id tr").length + $("#table2-id tr").length; // etc, for all table ID's.
}

或者,您可以向用户添加的行添加一个特殊类。

function countRows() {
  return $("tr.new").length;
}
于 2010-02-02T21:15:53.713 回答
0

您总是可以简单地为每个表使用一个变量来跟踪添加的行数。

或者另一种选择是使用 jQuery 的 data() 方法,它允许您将数据直接存储在 dom 元素中。click 事件会找到它的表,并在每次添加一行时更新表的 data() ,并在达到最大值时阻止进一步添加。

编辑:更正代码,检查 theCount 是否未定义,并删除错误放置的括号。

$('#Clone').click(function() {
    var $btn = $(this).parent();
    if($btn.closest('table').data('theCount') == undefined) {
        $btn.closest('table').data('theCount', 0)
    }
    var currentCount = $btn.closest('table').data('theCount');

    if(currentCount < 5) {
        $btn.closest('tr').clone(true).insertAfter($btn);
        $btn.closest('table').data('theCount', currentCount + 1);
    }
});

http://api.jquery.com/data/

于 2010-02-02T21:24:38.807 回答
0

您还可以使用表格上的数据属性

   var i = $('#tableID').data('userAddedRows');//of course you need to check there is a value and such
   i++;
   $('#tableID').data('userAddedRows',i);

然后只需检查以确保 i 小于允许的数量

于 2010-02-02T21:28:38.673 回答
0

感谢您的帮助,但我找到了一个可以解决问题的 JQuery 插件。是这里...

http://cloudgen.w0ng.hk/jquery/table.addrow.php

于 2010-02-03T18:54:36.110 回答