【问题标题】:How to select tr sibling and input on table如何选择 tr 兄弟并在表上输入
【发布时间】:2021-10-23 08:19:03
【问题描述】:

我在选择产品后尝试选择并获取价格,并在输入兄弟 tr 上返回价格。

我试试

function getPrice() {
  $(this).closest('tr').find('input').val($(this).val());
};

还有nth-child() 的变体,但我不能。

我需要更新价格值

<!-- Django template tags -->
{% for item in items %}
<tr>
  <td>
    <select name="product" class="form-control" onchange="getPrice()">
      <!-- Django template tags -->
      {% for product in products %}
        <option value="{{product.pk}}">{{ product.title }}</option>
      {% endfor %}
    </select>
  </td>
  <td>
    <input name="price" class="form-control price" type="number" step="0.01">
  </td>
  <td>
    <input name="quantity" class="form-control" type="number" step="0.01">
  </td>
  <td>
    <span class="span-is-link no" onclick="removeRow()">
      <i class="fa fa-close"></i>
    </span>
  </td>
</tr>
{% endfor %}

<script>
  function getPrice() {
    // Initial test with get value of select.
    // jQuery
    // inpuy in equivalent line of tr
    $(this).closest('tr').find('input').val($(this).val());
  }
</script>

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    您的getPrice() 函数不起作用,因为当您通过onchange HTML 属性调用它时,this 关键字将是window,即浏览器全局对象,而不是您的&lt;select&gt;元素。

    解决方案可能是将 HTML 中的 onchange 属性中的 getPrice() 替换为 getPrice.call(this)。这样,您的函数中的this 将是&lt;select&gt;

    <select name="product" class="form-control" onchange="getPrice.call(this)">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2017-04-13
      相关资源
      最近更新 更多