簡體   English   中英

通過父母的jQuery選擇器?

[英]Jquery selector via parents?

我有這個簡單的表(嵌套)

 <table border="1px">
            <tr>
                <th>kkkk</th>
                <th>mmmm</th>
            </tr>
            <tr>
                <td>a</td>
                <td>a</td>
            </tr>
            <tr>
                <td>a</td>
                <td>a</td>
            </tr>
            <tr>
                <td>a</td>
                <td>
                  <table border="1px" style="margin:10px">
                        <tr>
                            <th>xxxx</th>
                          <th style="background-color:yellow">yyyy</th>
                        </tr>
                        <tr>
                            <td>a</td>
                            <td>a</td>
                        </tr>
                        <tr>
                            <td>a</td>
                            <td>a</td>
                        </tr>
                        <tr>
                          <td >a</td>
                            <td  style="background-color:red;" class="theTd">a</td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

在此處輸入圖片說明

(這里沒有任何表格ID)

我想通過單擊red區域,找到yellow值所在的

我沒有獲取TH的索引的問題。

問題是我只想通過Parents()方法執行此操作-紅框看到2個具有TH ...的parents TR's TR。xxx,yyy行和kkk,mmm行...

就像是 :

  alert( $(".theTd").parents("first tr  parent which contains th's").....);

正確的選擇器語法是什么?

http://jsbin.com/udohum/1/edit

編輯

我不希望普通的parent()。parent()....導致.theTd可以在其中包含包裝Div等等,所以-這里的父母將是DIV。 (這會損害邏輯。

那這樣的東西呢?

$('.theTd').click(function(){
    alert($(this).parent().parent().find('tr > th:nth-child(2)').html());
});

(在這里查看它的工作原理: http : //jsfiddle.net/Te3QB/1/

更新:使用.closest()選擇器可能會更好:

$('.theTd').click(function(){
    alert($(this).closest('table').find('tr > th:nth-child(2)').html());
});

.closest()獲取與選擇器匹配的第一個元素,從當前元素開始,一直擴展到DOM樹。

parents()選擇選定元素的所有父級,您可以改用parentsUntil

$(".theTd").parentsUntil('table').find('th[style^=background]')

jsBin

closest()方法:

$(".theTd").closest('table').find('tr:has("th")').foo()

要獲取tr,請嘗試以下操作:

$(".theTd").closest("table").find("tr");

這個有點雜亂。 我們將需要第n個孩子,為此,我們需要索引:

$(this).closest('table').find('tr th:nth-child('+ ($(this).index()+1) +')');

暫無
暫無

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

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