2009-12-08 52 views
7
$(this).parents('table:first > tbody > tr') 

而且這兩個選擇器有什麼區別?

$(this).parents('table:first').children('tbody').children('tr') 
+3

使用最接近而非父母&:第一個 – redsquare 2009-12-08 02:47:46

+1

@redsquare:我們不知道他實際上想要選擇什麼。 – SLaks 2009-12-08 02:48:40

+0

==父母('表:第一') – redsquare 2009-12-08 02:50:22

回答

13

不同的是,第一選擇是完全在parents呼叫內,而第二個則不是。

因此,第一個查找匹配table:first > tbody > tr的所有父母this。 (換言之,含有trthis即在第一table

第二個將找到的this相匹配table:first母體,然後直接在tbody s表示母體的發現所有的tr S的。 (換句話說,所有的tr小號直接父表中的)

+3

似乎直觀的反。我第一次讀到第一個。我當然懶得去測試。 – ChaosPandion 2009-12-08 02:46:21

+0

@ChaosPandion:仔細閱讀。你會明白我的意思。 – SLaks 2009-12-08 02:47:47

+0

+1 - 好的,我仔細看過,終於明白了。 – ChaosPandion 2009-12-08 02:54:27

4

也許一個例子可以幫助...開始了這個HTML

<table border=1> 
<thead> 
    <th>Outter Table</th> 
</thead> 
<tbody> 
    <tr><td>1</td></tr> 
    <tr> 
    <td> 
    <table border=1 width=100> 
    <thead> 
     <th>Inner Table</th> 
    </thead> 
    <tbody> 
     <tr><td>2a</td></tr> 
     <tr><td class="test">2b</td></tr> 
     <tr><td>2c</td></tr> 
    </tbody> 
    </table> 
    </td> 
    </tr> 
    <tr><td>3</td></tr> 
</tbody> 
</table> 

應用此腳本:

$('.test').parents('table:first > tbody > tr').addClass('foo'); 
$('.test').parents('table:first').children('tbody').children('tr').addClass('bar'); 

結果:

<table border="1"> 
<thead> 
    <th>Outter Table</th> 
</thead> 
<tbody> 
    <tr class="foo"><td>1</td></tr> 
    <tr class="foo"> 
    <td> 
    <table width="100" border="1"> 
    <thead> 
     <th>Inner Table</th> 
    </thead> 
    <tbody> 
     <tr class="bar"><td>2a</td></tr> 
     <tr class="bar"><td class="test">2b</td></tr> 
     <tr class="bar"><td>2c</td></tr> 
    </tbody> 
    </table> 
    </td> 
    </tr> 
    <tr class="foo"><td>3</td></tr> 
</tbody> 
</table> 
+0

這也不錯! – user198729 2009-12-08 04:05:06