2010-05-24 70 views
6

我想插入一个块元素在另一个之前插入一些东西。我不确定我是否使用正确的方法,但这里是我的代码。希望你们能帮忙。谢谢!Jquery插入元素<tr>

jQuery的

$("#addMatch").click(function(){ 

    $("<td>New insert</td>").insertBefore("#addMatch").closest('tr'); 

    return false; //this would insert the <td>New insert</td> before the    
        //<td><input type="button" id="addMatch" name="addMatch" value="Add 
        //Match" </td> but not <tr> 
}); 

的Html

<tr> 
<td>some data</td> 
</tr> 

//can't tell how many tr would show before the last "addMatch" button. It's dynamic. 
// I want the <td>New insert</td> show up here. 
    <tr> 
    <td><input type="button" id="addMatch" name="addMatch" value="Add Match" </td> 
    </tr> 

回答

13

<td>应始终处于<tr>

我很可能会令你的函数是这样的:

$("#addMatch").click(function(){ 
    $(this).parents('tr:first').before('<tr><td>New Insert</td></tr>'); 
    return false; 
}); 
+2

相反。家长的'( 'TR:第一')',还有'.closest( 'TR')':) – 2010-05-24 23:42:00

+0

是.closest快? – 2010-05-24 23:44:06

+0

好的。谢谢!是的,我认为最接近更快。 – FlyingCat 2010-05-24 23:45:32