2010-05-24 4 views
6

J'essaie d'insérer un élément de bloc Insérer quelque chose avant un autre. Je ne suis pas sûr si j'utilise la bonne méthode mais voici mon code. J'espère que vous pouvez aider. Merci!Jquery Insérer un élément avant <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> 

Répondre

13

<td> doit toujours être dans un <tr>.

je serais probablement faire de votre fonction comme ceci:

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

Au lieu de '.parents ('tr: first')', il y a '.closest ('tr')' :) –

+0

est .closest plus rapide ? –

+0

Bon. Merci! Oui, je pense que le plus proche est plus rapide. – FlyingCat

Questions connexes