[英]In jQuery, how do you select current table TR but not any nested table TR?
所以我嘗試了這個:
input.find(" tr").each(function(){ ... });
我也試過這個:
input.find(" > tr").each(function(){ ... });
這兩個都不起作用。 第一個將選擇任何TR,即使它在嵌套表下也是如此。 如果桌子有肢體或類似的東西,第二個將不起作用。 有什么幫助嗎?
輸入定義為:
var input = $(".mySelectionScope");
DOM如下所示:
<div class='mySelectionScope'>
<div> // Optional
<table>
<tbody>
<tr> // Select this one
<table>
<tr> // Don't select this one
....
您可以使用.not()在tr的下面過濾掉tr的內容
input.find("tr").not("tr tr")
您可以過濾它:
input.find("tr").filter(function(){return !$(this).closest('tr').length}).each(...);
調用trs列表上的first()怎么樣?
使用jQuery children()而不是find()
從文檔:
.children()方法與.find()的不同之處在於,.children()僅沿DOM樹向下移動一個級別,而.find()可以向下遍歷多個級別以選擇后代元素(孫子等)。
可選的div也會帶來一些棘手的問題...
var input = $('.mySelectionScope').children('div').length == 0 ?
$('.mySelectionScope') :
$('.mySelectionScope > div'),
rows = input.children('table').children('tbody').length == 0 ?
input.children('table').children('tr') :
input.children('table').children('tbody').children('tr');
如果在所有瀏覽器中始終插入了tbody,則不需要第二個if語句,而可以使用
rows = input.children('table').children('tbody').children('tr');
非常難看,但您不能僅憑選擇器來做到這一點。
使用此解決方案,之間是否有tbody標簽並不重要:
$('table').find('tr:first').parent().children()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.