简体   繁体   中英

Using jQuery how to select each td in a tr, table by table

In my interface I have multiple tables. I want to go to each “td” in a “tr” table by table. If I use this way, code can't identify tables,

$(function() {
    $('tr').each(function() {
        // For each row
        $(this).find('td').each(function(i) {
           // code to be execute 
        });

    });
});

It works like this, execute first column in all tables and then go to second column. I want to do this, execute first column in first table then go to second column in first table and execute second table as first table

This is happens with above code 这是上面的代码

This is what I want to do 这就是我想做的

Can someone please help me to do that, thank you...

You can do something like this using the index of table and column

 $(function() { $('table').each(function(ind) { $(this).find('tr').each(function() { $(this).find('td').each(function(i) { $(this).text(ind * 2 + i + 1); }); }); }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> 

Also You can do the following if column count is different

 $(function() { var i = 1; $('table').each(function(ind) { $table = $(this); $(this).find('tr:first').each(function() { $(this).find('td').each(function(i1) { $table.find('tr td:nth-child(' + (i1 + 1) + ')').text(i++); }); }); }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> <table> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> 

Change your selector to select each td. $("tr td").each(fn...

You need to use nested each like:

$(function() {
    $('table').each(function() {

        $(this).find('tr').each(function(i) {
               $(this).find('td').each(function(i) {
                        // code to be execute 
                });
        });

    });
})

;

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