簡體   English   中英

得到第一個N <tr> 具有 <td> 小時候使用jQuery

[英]Get first N <tr> that has <td> as child using jQuery

我有一個具有行的<table> ,第一行是課程標題​​,其他10個非標題行。 我想獲得前3個非標題行(簡單來說就是td child not th

<table>
    <tr>
        <th> Header 1 </th>
        <th> Header 2 </th>
        <th> Header 3 </th>
    </tr>
    <tr>
        <td> Row 1 Cell 1 </td>
        <td> Row 1 Cell 2 </td>
        <td> Row 1 Cell 3 </td>
    </tr>
    <tr>
        <td> Row 2 Cell 1 </td>
        <td> Row 2 Cell 2 </td>
        <td> Row 2 Cell 3 </td>
    </tr>
</table>

我正在使用JQuery

var sideNotification = jq(jq.parseXML(response.d))
    .find('tr').has("td")
    .each(function (index) {
        if (index < 3) {
            return {
                leadNo: $(this).find("td:eq(0)").text(),
                product: $(this).find("td:eq(1)").text(),
                status: $(this).find("td:eq(2)").text()
            }
        }
    });
console.log(sideNotification.length);

但是它仍然返回10作為計數。 怎么解決呢?

您可以結合使用:has:lt選擇器。

$('tr:has(td):lt(3)').css('color', 'red');
   ^^^^^^^^^^^^^^^
   ^^               tr       -->  Select all tr elements
     ^^^^^^^        :has(td) -->  Select all tr elements having `td` as descendent
             ^^^^^  :lt(3)   -->  Get first three elements

 $('tr:has(td):lt(3)').css('color', 'red'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <table> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> </tr> <tr> <td>Row 1 Cell 1</td> <td>Row 1 Cell 2</td> <td>Row 1 Cell 3</td> </tr> <tr> <td>Row 2 Cell 1</td> <td>Row 2 Cell 2</td> <td>Row 2 Cell 3</td> </tr> <tr> <td>Row 1 Cell 1</td> <td>Row 1 Cell 2</td> <td>Row 1 Cell 3</td> </tr> <tr> <td>Row 2 Cell 1</td> <td>Row 2 Cell 2</td> <td>Row 2 Cell 3</td> </tr> <tr> <td>Row 1 Cell 1</td> <td>Row 1 Cell 2</td> <td>Row 1 Cell 3</td> </tr> <tr> <td>Row 2 Cell 1</td> <td>Row 2 Cell 2</td> <td>Row 2 Cell 3</td> </tr> </table> 

你可以這樣使用

$("tr:lt(4)").filter(function () {
   return $(this).find("td").length > 0;
})
  1. :lt(4)將獲取所有索引小於4的tr元素。
  2. 然后,可以通過檢查每個tr中的td計數來消除標題。

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM