Javascript 使用jQuery从单击的元素获取最接近的输入值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8660269/
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
Getting closest input value from clicked element with jQuery
提问by David
I have the following markup:
我有以下标记:
<div class="options">
<div class="quantity">
<label>Qty:</label>
<input type="text" name="quantity" value="1"/>
</div>
<div class="buttons">
<a href="#" class="add">Add Item</a>
</div>
</div>
I have a click event binded to the 'add' class using jQuery. When I click that, I'd like to get the value of name="quantity", but there are several places that 'add' is clicked and several quantity fields.
我有一个使用 jQuery 绑定到“添加”类的点击事件。当我点击它时,我想获得 name="quantity" 的值,但是有几个地方点击了“添加”和几个数量字段。
I'm trying to get the 'closest' input value. I've tried using 'closest' and 'findall' , but no luck.
我正在尝试获得“最接近”的输入值。我试过使用 'closest' 和 'findall' ,但没有运气。
Any idea how I can get this using jQuery? Thank you!
知道如何使用 jQuery 获得它吗?谢谢!
回答by Andrew Whitaker
$(".add").on("click", function () {
var val = $(this).closest("div.options").find("input[name='quantity']").val();
});
The strategy here is:
这里的策略是:
- Use
closest
to find the closest ancestor matching the given selector (in this case adiv
with classoption
) - Then use
find
to find theinput
with the givenname
using the attribute equals selector. - Finally, use
val
to retrieve the value of theinput
.
- 使用
closest
找到最近的祖先给定的选择匹配(在这种情况下,div
用类option
) - 然后使用属性 equals 选择器
find
来查找input
给定name
的。 - 最后,使用
val
来检索 的值input
。
回答by Matti Virkkunen
You need to use closest
to find the proper enclosing element and then work from there.
您需要使用closest
找到合适的封闭元素,然后从那里开始工作。
$(link).closest(".options").find("input[name=quantity]")
回答by Dominic Green
$(this).parent().parent().find("input[name=quantity]").val()
This should do the trick
这应该可以解决问题
回答by Kristian
I guess closest works only with same level elements. so..
我猜最接近的作品仅适用于相同级别的元素。所以..
Why not to put id to the input field and select by $('#input-id')
?
为什么不将 id 放入输入字段并选择 by $('#input-id')
?
Or traverse up to class options and find input in there: $(this).parents('.options:first').find('input');
或者遍历类选项并在那里找到输入: $(this).parents('.options:first').find('input');