使用 JQuery 限制动态添加的表行数
我使用克隆动态地将一行插入到带有 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 的表,因此它需要与页面上的多个表一起使用。
希望你能帮忙。
I am dynamically inserting a row into a table with JQuery using clone.
$('#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);
});
The end user will control the insertion of new rows. I need to limit the number of new rows to 5. Is there a way to do this with a cookie or some other method (array). I could have multiple tables with there own unique id so it needs to work with multiple tables on the page.
Hope you can help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
变量怎么样?
或者,您也可以对用户添加的类设置不同的类,然后在添加函数中对它们进行计数。
How about a variable?
Alternatively, you could also set a different class on the user-added ones and then just count them inside your add function.
您始终可以简单地为每个表使用一个变量来跟踪添加的行数。
或者另一种选择是使用 jQuery 的 data() 方法,它允许您直接将数据存储在 dom 元素中。单击事件将找到其表,并在每次添加行时更新表的 data() ,并在达到最大值时阻止进一步添加。
编辑:更正了代码,检查 theCount 是否未定义,并删除错误放置的括号。
http://api.jquery.com/data/
You could always simply use a variable for each table to track the number of added rows.
Or another alternative would be to use jQuery's data() method which allows you to store data in a dom element directly. The click event would find its table, and update the table's data() each time a row is added, and prevent further additions when it reaches the maximum.
EDIT: Corrected code with check to see if theCount is undefined, and to remove a mis-placed parentheses.
http://api.jquery.com/data/
您可以只计算返回的元素数量。
或者,您可以向用户添加的行添加一个特殊的类。
You could just count the number of elements returned.
Or, you could add a special class to the user-added rows.
您还可以使用表上的数据属性
然后只需检查以确保 i 小于允许的数量
You could also use the data attribute on the table
Then just check to make sure the i is less than the amount allowed
感谢您的帮助,但我找到了一个可以解决问题的 JQuery 插件。它在这里...
http://cloudgen.w0ng.hk/jquery/table。 addrow.php
Thanks for your assistance but I found a JQuery Plugin that does the trick. It is here...
http://cloudgen.w0ng.hk/jquery/table.addrow.php