[英]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');
})
成一個功能?
試着這樣做:
$('.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.