简体   繁体   English

使用jQuery从单击的元素获取最接近的输入值

[英]Getting closest input value from clicked element with jQuery

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.我有一个使用 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.当我点击它时,我想获得 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?知道如何使用 jQuery 获得它吗? Thank you!谢谢!

$(".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 a div with class option )使用closest的找到与给定选择器匹配的最近祖先(在这种情况下是一个带有 class optiondiv
  • Then use find to find the input with the given name using the attribute equals selector .然后使用find使用属性 equals selector查找具有给定nameinput
  • Finally, use val to retrieve the value of the input .最后,使用val检索input的值。

您需要使用closest来找到合适的封闭元素,然后从那里开始工作。

$(link).closest(".options").find("input[name=quantity]")
$(this).parent().parent().find("input[name=quantity]").val()

这应该可以解决问题

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 放入输入字段并按$('#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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM