2013-07-27 40 views
1

http://jsfiddle.net/twkRY/最接近()從之前的TD

<table> 
    <tr> 
     <td class="iwant">ttt</td> 
     <td>some text <span class="txt">haha</span></td> 
    </tr> 
</table> 

$(".txt").on("click", function() { 
    alert($(this).closest("td.iwant").html()) 
}) 

得到一個HTML值它只是給不確定的。爲什麼不ttt

編輯:我知道解決如何使其與prevparent工作,我只是想知道爲什麼closest不起作用。

+1

'jQuery.closest()'遍歷* *了,你想'jQuery.prev()'或'jQuery.prevAll( 'iwant')'。 –

+0

'jQuery.closest()'更類似於'jQuery.parents()'。 –

+0

'closest'不起作用,因爲'td.iwant'不是'.txt'元素的父親 –

回答

1

您想獲得closesttd,然後通過prev獲得之前的兄弟姐妹。

$(this).closest("td").prev(".iwant").html() 
+0

'prevAll'可能在一般情況下使用,或'prev'在沒有選擇器的情況下使用 –

+0

@evening - 這樣做的原因是您想要得到的'td'(顯然在所有情況下)不是'.txt'的祖先,所以'.closest()'不能線性向上查找。你正在尋找祖先的兄弟姐妹。根據用例,我可能會使用'.prevAll()'橫向移動而不是'.prev()',除非'.prev()'做了我不知道的事情? –

+1

'.prevAll()'將[覆蓋更多地區](http://jsfiddle.net/vDNGN/)。 –

相關問題