简体   繁体   中英

How to select a value of a row in a table with jquery?

I want to get the value of a row in a table with jquery, when the user click on it.

I have tried this solution, but it doesn't work correctly:

 $(document).ready(function() { $.post("./php/myjson.php", function(data, status) { obj = JSON.parse(data); var trHTML = ''; for (var i = 0; i < obj.giocatori.length; i++) { trHTML += '<tr><td><img src="../media/image/squadre/' + obj.giocatori[i].Squadra.toLowerCase() + '.png"/></td><td>'+obj.giocatori[i].Giocatore+'</td><td>' + obj.giocatori[i].Cognome + '</td><td>' + obj.giocatori[i].Prezzo + '</td></tr>'; } trHTML+='</tbody>'; $('#records_table').append(trHTML); }); $( "#records_table tr" ).on( "click", function( ) { alert( $(this).find('td:nth-child(2)').html()); }); }); 
 table tbody tr:hover { background-color: orange; cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="records_table" border="1"> <tbody> <tr> <th>Squadra</th> <th>ID</th> <th>Cognome</th> <th>Prezzo</th> </tr> </table> 

Where is the error ?

Even though the table exists when the page loads, its contents are loaded after the page loads (after DOM ready event). You want to use a delegated event. Therefore, try this:

$( "#records_table" ).on( "click", "tr", function(  ) {
    alert( $('td', this).eq(2).html() );
});

NOTE : Adding this section -- your version -- in the success call back of the the ajax call after the new content is added should also work.

You are keeping tbody in HTML, but adding the content to table. Please change the following.

$(document).ready(function() {

            $.post("./php/myjson.php", function(data, status) {
                obj = JSON.parse(data);
                var trHTML = '';
                for (var i = 0; i < obj.giocatori.length; i++) {

                    trHTML += '<tr><td><img src="../media/image/squadre/' + obj.giocatori[i].Squadra.toLowerCase() + '.png"/></td><td>'+obj.giocatori[i].Giocatore+'</td><td>' + obj.giocatori[i].Cognome + '</td><td>' + obj.giocatori[i].Prezzo + '</td></tr>';
                }
                $('#records_table tbody').append(trHTML);

            });
            $( "#records_table tr" ).on( "click", function(  ) {
                  alert( $(this).find('td:nth-child(2)').html());
            });

        });

as well as you can close the tbody in HTML.

Squadra ID Cognome Prezzo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM