Jquery找到最近的匹配元素

imp*_*335 58 jquery dom-traversal

我有一系列带有列的行,我想选择一个input字段的值,该字段位于input字段(价格输入)的前一列中,我在释放键时调用函数.

我试过了:

quantity = $(this).parent().parent().children().val() ;
quantity = $(this).parent().parent().children().closest('.inputQty', this).val() ;
Run Code Online (Sandbox Code Playgroud)

但是没有工作.

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>
Run Code Online (Sandbox Code Playgroud)

Utk*_*nos 122

var otherInput = $(this).closest('.row').find('.inputQty');
Run Code Online (Sandbox Code Playgroud)

这会达到行级别,然后再降低到.inputQty.

  • 这个问题不是关于在同一级别上找到一些东西 - 有必要先上后退 - 但是是的,对于同一级别有`.siblings()`和各种`next~()`和`prev~( )` 方法。 (2认同)
  • 谢谢我正在寻找这样的解决方案,它对我有用!但最重要的是我学到了更多关于nearest()函数的知识.非常感谢!达维德 (2认同)

ade*_*neo 10

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

$(this).closest('.row').children('.column').find('.inputQty').val();
Run Code Online (Sandbox Code Playgroud)