这是我必须使用的HTML。 spacer
类基本上缩进了文本。
<table>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 2
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 2
</td>
</tr>
</table>
我应该如何构建我的jQuery选择器,以便我能够获取标题的行?和副标题?
我已经尝试了$(tr).has('td.spacer')
,但这并不是真的有用,因为他们都使用它并且有倍数(#34;标题为#34; 3为&#34;副标题& #34)
答案 0 :(得分:1)
您可以过滤
var f = function(n) {
return function() {
return $(this).find('.spacer').length === n;
}
}
var headings = $('td').filter( f(2) );
var subheading = $('td').filter( f(3) );
// ..etc
var f = function(n) {return function() {return $(this).find('.spacer').length === n}};
$('td').filter( f(2) ).css('color','red');
$('td').filter( f(3) ).css('color','blue');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 2
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 2
</td>
</tr>
</table>
&#13;
答案 1 :(得分:1)
根据.spacer
span元素的数量获取。使用:has()
,:not()
和:nth-child()
伪类选择器的组合。
// get head - which don't have 3rd `spacer` element
$('tr:has(:not(td .spacer:nth-child(3)))').css('color', 'green');
// get subhead - which have 3rd `spacer` element
$('tr:has(td .spacer:nth-child(3))').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 2
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 2
</td>
</tr>
</table>