如何使用jQuery迭代HTML页面中每个表的所有表行

时间:2012-09-24 11:40:42

标签: jquery html css

我需要正确的语法来在彼此内部编写两个循环。第一个循环遍历html页面中的每个表,没有id或类,第二个遍历jQuery中第一个循环指定的表的每个表行。

这是我的jQuery,但它的工作可能不正确。

$(document).ready(function(){
    $('table.rep').each(function(){
        $(this + ' tr').each(function{
            // change style of this tr
        });
    });
 });

3 个答案:

答案 0 :(得分:0)

你这样做(使用jQuery上下文参数来限制搜索表中的tr元素:

$(document).ready(function(){
    $('table.rep').each(function(){
        $('tr', this).each(function{
             // change style of this tr
        });
    });
});

或者,像这样(使用find方法查找位于jQuery对象所代表的元素内的元素,并调用方法):

$(document).ready(function(){
    $('table.rep').each(function(){
        $(this).find('tr').each(function{
             // change style of this tr
        });
    });
});

你甚至不必根据你想做的事情来嵌套循环,只需循环遍历所有表行即可:

$('table tr').each(function(){
    // change tr style
});

答案 1 :(得分:0)

或者这个:

$('table.rep tr').each(function(){
   ...        
});

答案 2 :(得分:0)

<script>
    $(document).ready(function () {
        $('table.rep').each(function () {
            $(this).find('tr').each(function () {
            // Do your stuff
            });
        });
    });

 </script>