jQuery每个表行中的循环 [英] jQuery each loop in table row

查看:23
本文介绍了jQuery每个表行中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

<tr><td><table id="tblTwo"><tr><td>项目</td></tr><tr><td>产品</td></tr></tbody>
</td></tr><tr><td>第 1 项</td></tr><tr><td>第 2 项</td></tr></tbody>

我已经编写了 jQuery 来循环遍历每个 tr,例如:

$('#tblOne tr').each(function() {...code...});

但问题是它循环遍历tblTwo"的tr"也是我不想要的.任何人都可以提出解决此问题的建议吗?

解决方案

在 jQuery 中只需使用:

$('#tblOne > tbody > tr').each(function() {...code...});

使用子选择器(>),您将遍历所有子项(而不是所有后代),例如三行:

$('table > tbody > tr').each(function(index, tr) {控制台日志(索引);控制台日志(tr);});

结果:

<预><代码>0<tr>1<tr>2<tr>

<小时>

VanillaJS 中,您可以使用 document.querySelectorAll() 并使用 forEach()

遍历行

[].forEach.call(document.querySelectorAll('#tblOne > tbody > tr'), function(index, tr) {/* 控制台日志(索引);*//* 控制台日志(tr);*/});

I am having something like:

<table id="tblOne">
            <tbody>
                <tr>
                    <td>
                        <table id="tblTwo">
                            <tbody>
                                <tr>
                                    <td>
                                        Items
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        Prod
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td>
                        Item 1
                    </td>
                </tr>
                <tr>
                    <td>
                        Item 2
                    </td>
                </tr>
            </tbody>
        </table>

I have written jQuery to loop through each tr like:

$('#tblOne tr').each(function() {...code...});

But problem is that it loops through the "tr" of "tblTwo" also which I don't want. Can anyone please suggest something to solve this?

解决方案

In jQuery just use:

$('#tblOne > tbody  > tr').each(function() {...code...});

Using the children selector (>) you will walk over all the children (and not all descendents), example with three rows:

$('table > tbody  > tr').each(function(index, tr) { 
   console.log(index);
   console.log(tr);
});

Result:

0
<tr>
1 
<tr>
2
<tr>


In VanillaJS you can use document.querySelectorAll() and walk over the rows using forEach()

[].forEach.call(document.querySelectorAll('#tblOne > tbody  > tr'), function(index, tr) {
    /* console.log(index); */
    /* console.log(tr); */
});

这篇关于jQuery每个表行中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆