jQuery 如何在当前 <tr> 之后追加新的 <tr>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3599874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append new <tr> after current <tr>
提问by Bharat Patil
I have following table structure.
我有以下表格结构。
<table>
<tr>
<td><a href="#"></td>
</tr>
</table>
When I click on <a>
I want to add new <tr>
next to <tr>
of which <a>
is clicked.
当我点击<a>
我要添加新的<tr>
旁边,<tr>
其中<a>
被点击。
So the result will be:
所以结果将是:
<table>
<tr>
<td><a href="#"></td>
</tr>
<tr>
<td><a href="#"></td>
</tr>
</table>
回答by jAndy
Example:
例子:
$('a').bind('click', function(){
$('<tr><td>new td</td></tr>').insertAfter($(this).closest('tr'));
});
If you want to create a clone use:
如果要创建克隆,请使用:
$('a').live('click', function(){
var $this = $(this),
$parentTR = $this.closest('tr');
$parentTR.clone().insertAfter($parentTR);
});
Example link: http://www.jsfiddle.net/7A6MQ/
示例链接:http: //www.jsfiddle.net/7A6MQ/
Basically, you create a copy from the tr element
(which includes child nodes) and insert that copy after that element. Therefore, you need the .live
binding to make sure that newly created a
elements do also invoke that click handler.
基本上,您从tr element
(包括子节点)创建一个副本并在该元素之后插入该副本。因此,您需要.live
绑定以确保新创建的a
元素也调用该单击处理程序。
Ref.: .clone(), .insertAfter(), .live()
回答by Rock'n'muse
Also, you can write:
另外,你可以写:
$('a').bind('click', function () {
$(this).closest('tr').after('<tr><td>new td<td></tr>');
});
Not so much difference but looks more readable.
没有太大区别,但看起来更具可读性。
回答by Pritesh Chaudhari
Here is the code. Please check and let me know if there is any issue.
这是代码。请检查并让我知道是否有任何问题。
function AddRaw(obj){
var $this = obj;
$parentTR = $this.closest('tr');
$parentTR.clone().insertAfter($parentTR);
}