Jquery 查找最近的匹配元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11756529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:55:01  来源:igfitidea点击:

Jquery find nearest matching element

jquerydom-traversal

提问by imperium2335

I have a series of rows with columns and I want to select the value of an inputfield that is in a previous column to the inputfield (price input) that I am calling a function on when a key is released.

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

I have tried:

我试过了:

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

But neither work.

但两者都不起作用。

An example of the DOM:

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>

回答by Utkanos

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

That goes up to a row level, then back down to .inputQty.

这上升到行级别,然后回到.inputQty.

回答by adeneo

closest()only looks for parents, I'm guessing what you really want is .find()

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

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

回答by Esailija

Get the .columnparent of the thiselement, get its previous sibling, then find any input there:

获取元素的.columnthis元素,获取它的前一个兄弟元素,然后在那里找到任何输入:

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

Demo: http://jsfiddle.net/aWhtP/

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

回答by Alex

You could try:

你可以试试:

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

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