2010-05-24 125 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