【问题标题】:Get value of input in parent parent parent获取父级父级中的输入值
【发布时间】:2020-08-26 14:07:02
【问题描述】:

我有一个包含几行表格的页面(生成了 HTML,我无法修改它)。在每一行中,有 2 个输入(不同的列)。当我修改其中一个输入的值(使用“qty”类名)时,我想检索第二个输入的值,但我做不到。注意行数不固定

我生成的 html 和尝试

jQuery('.qty').on('change', function() {
  console.log(jQuery(this).val());
  console.log($(this).closest("tr").children('.product_quantity').children('input').val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
      <th class="product-quantity">Quantity 1</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="product-name">Name product 1</td>
      <td>$1,00</td>
      <td class="product-quantity">
        <input type="number" min="1" step="1" name="items[45955][quantity]" value="4">
      </td>
      <td>
        <div>
          <input type="number" class="qty" step="1" min="0" max="" name="quantity" value="1" title="Qté" size="4" placeholder="" inputmode="" kl_vkbd_parsed="true">
        </div>
      </td>
    </tr>
    <tr>
      <td class="product-name">Name product 1</td>
      <td>$1,00</td>
      <td class="product-quantity">
        <input type="number" min="1" step="1" name="items[45955][quantity]" value="4">
      </td>
      <td>
        <div>
          <input type="number" class="qty" step="1" min="0" max="" name="quantity" value="1" title="Qté" size="4" placeholder="" inputmode="" kl_vkbd_parsed="true">
        </div>
      </td>
    </tr>
  </tbody>
</table>

我试图通过父母和许多其他测试最接近改变,但我做不到 你能帮我吗?

【问题讨论】:

  • closest('tr').find('input').eq(1) 获取第二个
  • 在&lt;tr&gt; 上添加id="product-xxxx" 可能不会有什么坏处?这样您也可以将用户发送到该产品,也许创建一些:target 样式并通过执行以下操作稍微简化最近的目标:closest('[id^=”product-”]').find(...)
  • 请注意,第二个输入绝不是第一个输入的“父级”(基于 parent-parent-parent 的标题)
  • 请注意,$(".product_quantity") 将不会找到 &lt;td class="product-quantity"&gt; "_" !== "-" - 修复错字(在两行中更改为 class='product_quantity')并且您的代码可以正常工作。

标签: javascript jquery


【解决方案1】:

我假设您想在更改数量值时获取 Action Value

试试这个

$('.product-quantity input').on('keyup', function () {
    console.log($(this).val());
    console.log($(this).parent('td').next('td').find('div input').val());
})

【讨论】:

    【解决方案2】:

    试试这个:

    $(this).parent().parent().parent().find(".product-quantity input").val();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 2015-05-09
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多