簡體   English   中英

jQuery找到最高的父TD

[英]jQuery find highest parent TD

我正在處理表中包含的表單的代碼。 我正在編寫(使用jQuery)一個函數來突出顯示每個<input>元素的父<td> 那部分很簡單 - 代碼只是:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })

更復雜的部分是一些文本字段位於嵌套在第一個表的<td>中的第二個表中。 它看起來像:

<table>
    <tr>
        <td> <--cell I want to add the class to
            <table>
                <tr>
                    <td><input type='text'></td>
                </tr>
            </table>
        </td>
     </tr>
</table>

所以我的問題是:有沒有辦法使用一個jQuery語句來找到<input>元素的最高父<td> 換句話說,我可以結合:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })

$('.myForm input').click(function(){
    $(this).parent().parent().addClass('active');
    })

成一個功能?

最好的解決方案是在實際想要定位的表中添加一個類。 這意味着你可以通過像$(this).closest('.targetElement').addClass('active')這樣的東西來更新標記,而不必破壞JS。

如果你不能這樣做,你可以使用parents('td').last() 這將選擇所有td父元素,然后獲取最后一個元素。

$('.myForm input').click(function(){
    $(this).parents('td').last().addClass('active');
})

請參閱jQuery手冊:

試着這樣做:

$('.myForm input').click(function(){
   $(this).parents('td').last().addClass('active');
})

我建議嘗試:

 $(this).parents("td").last()

它將找到當前元素的所有表格單元格祖先。 最后一個應包含最高級別的表格單元格元素。

你可以試試:

$(this).parents('td:last');

要么

$(this).parents('td').last();

為您的頂級td元素提供一個類名:

<table>
    <tr>
        <td class="topTD"> <--cell I want to add the class to
            <table>
                <tr>
                    <td><input type='text'></td>
                </tr>
            </table>
        </td>
     </tr>
</table>


$('.myForm input').click(function(){
   $(this).closest('td.topTD').addClass('active');
});

又臟又臟:)

$(this).parents('td')[--$(this).parents('td').length]

暫無
暫無

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

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