[英]Get first N <tr> that has <td> as child using jQuery
I have a <table>
that has rows, first row is of-course header and other 10 non header rows. 我有一个具有行的<table>
,第一行是课程标题,其他10个非标题行。 I want to get top 3 non-header rows (simply that has td
child not th
) 我想获得前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>
I am using JQuery 我正在使用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);
But it still return 10 as count. 但是它仍然返回10作为计数。 How to solve it? 怎么解决呢?
You can use combination of :has and :lt selectors. 您可以结合使用: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>
You can use like this 你可以这样使用
$("tr:lt(4)").filter(function () {
return $(this).find("td").length > 0;
})
:lt(4)
will get all the tr elements whose index is less than 4. :lt(4)
将获取所有索引小于4的tr元素。 td
in each tr. 然后,可以通过检查每个tr中的td
计数来消除标题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.