使用jQuery从单击的元素中获取最接近的输入值 [英] Getting closest input value from clicked element with jQuery
本文介绍了使用jQuery从单击的元素中获取最接近的输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下标记:
<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>
我有一个使用jQuery绑定到'add'类的click事件.当我单击该按钮时,我想获取name ="quantity"的值,但是在多个位置单击了添加",并在多个数量字段中输入了数量".
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.
我正在尝试获取最接近的"输入值.我尝试使用'closest'和'findall',但是没有运气.
I'm trying to get the 'closest' input value. I've tried using 'closest' and 'findall' , but no luck.
有人知道我如何使用jQuery来获得它吗?谢谢!
Any idea how I can get this using jQuery? Thank you!
推荐答案
$(".add").on("click", function () {
var val = $(this).closest("div.options").find("input[name='quantity']").val();
});
这里的策略是:
- 使用
closest
查找与给定选择器匹配的最接近祖先(在这种情况下是div
,其类为option
) - 然后使用
查找
查找输入
使用给定的name
使用属性等于选择器. - 最后,使用
val
来检索的值输入
.
- 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
.
这篇关于使用jQuery从单击的元素中获取最接近的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文