2012-08-01 283 views
49

我有一系列的行,我想選擇一個input字段的值,該字段位於input字段(價格輸入)的上一列,當我調用函數時鍵被釋放。jquery查找最接近的匹配元素

我曾嘗試:

quantity = $(this).parent().parent().children().val() ; 
quantity = $(this).parent().parent().children().closest('.inputQty', this).val() ; 

但無論工作。

DOM的一個例子:

<div class="row"> 
    <div class="column"><input class="inputQty" id="quantity0" /></div> 
    <div class="column"><input class="someOther" id="Other0" /></div> 
    <div class="column"> 
     <div class="cSelect"> 
      <select id="currency0"><option>£</option></select> 
      <input class="price" id="price0" /> 
     </div> 
    </div> 
</div> 

回答

104
var otherInput = $(this).closest('.row').find('.inputQty'); 

也上升到一個行級,然後重新登錄。

+0

有沒有其他函數尋找與你當前所在的元素處於同一級別的東西?你總是不得不上去和下去? – Majo0od 2016-01-11 19:41:19

+0

這個問題不是關於在同一級別上找到某些東西 - 有必要上去然後回落 - 但是,對於同一級別有'.siblings()'和各種'next〜()'和'prev〜 ()'方法。 – Utkanos 2016-01-11 20:22:53

+2

謝謝我正在尋找這樣的解決方案,它爲我工作!但最重要的是我瞭解更多關於最接近()函數。非常感謝! Davide, – 2016-08-03 23:12:08

1

獲取.columnthis元素,獲得其以前的兄弟,然後找任何輸入有:

$(this).closest(".column").prev().find("input:first").val(); 

演示:http://jsfiddle.net/aWhtP/

0

您可以嘗試:

$(this).closest(".column").prev().find(".inputQty").val();

10

closest()只尋找父母,我猜你真正想要的是.find()

$(this).closest('.row').children('.column').find('.inputQty').val();