2010-05-24 10 views
6

Estoy tratando de insertar un elemento de bloque Insertar algo antes que otro. No estoy seguro si estoy usando el método correcto, pero aquí está mi código. Espero que puedan ayudar. ¡Gracias!Jquery Insertar elemento antes de <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> 

Respuesta

13

<td> siempre debe estar en un <tr>.

que probablemente hacer su función como esta:

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

en lugar de '.parents ('tr: first')', 'hay .closest ('tr')' :) –

+0

es más rápido .closest ? –

+0

Bueno. ¡Gracias! Sí, creo que lo más cercano es más rápido. – FlyingCat

Cuestiones relacionadas