仅从一个特定值更改值

时间:2018-11-16 12:05:41

标签: javascript jquery html input

我有一组生成的输入,其任务是将商品添加到商店列表并将值添加到sessionStorage密钥:

enter image description here

$('.increment').click(function increment() {
  $('.quantity-input').val(function(i, oldval) {
    return parseInt(oldval, 10) + 1;
  });
});


$('.drecement').click(function increment() {
  $('.quantity-input').val(function(i, oldval) {
    return parseInt(oldval, 10) - 1;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter-container">
  <input class="quantity-input" id=" 
       <?php echo $id_produtos; ?>" type="text" value="1">
  <div class="btn-container">
    <button id="<?php echo $id_produtos; ?>" class="btn-arrow 
        increment">▲</button>
    <button id="<?php echo $id_produtos; ?>" class="btn-arrow 
        drecement">▼</button>
  </div>
</div>

<div class="counter-container">
  <input class="quantity-input" id=" 
       <?php echo $id_produtos; ?>" type="text" value="1">
  <div class="btn-container">
    <button id="<?php echo $id_produtos; ?>" class="btn-arrow 
        increment">▲</button>
    <button id="<?php echo $id_produtos; ?>" class="btn-arrow 
        drecement">▼</button>
  </div>
</div>

问题是我还要更改其他生成的输入:

enter image description here

如何仅更改我单击的输入?

1 个答案:

答案 0 :(得分:2)

您需要使用$(this)来引用相关输入,方法是使用.closest('.counter-container')转到父div,然后使用.find('.quantity-input')选择所需的输入,例如:

$(this).closest('.counter-container').find('.quantity-input').val(...

$('.increment').click(function increment() {
  $(this).closest('.counter-container').find('.quantity-input').val(function(i, oldval) {
    return parseInt(oldval, 10) + 1;
  });
});


$('.drecement').click(function increment() {
  $(this).closest('.counter-container').find('.quantity-input').val(function(i, oldval) {
    return parseInt(oldval, 10) - 1;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter-container">
  <input class="quantity-input" id="x_1" type="text" value="1">
  <div class="btn-container">
    <button id="1" class="btn-arrow increment">▲</button>
    <button id="1" class="btn-arrow drecement">▼</button>
  </div>
</div>

<div class="counter-container">
  <input class="quantity-input" id="x_2" type="text" value="1">
  <div class="btn-container">
    <button id="y_2" class="btn-arrow increment">▲</button>
    <button id="z_2" class="btn-arrow drecement">▼</button>
  </div>
</div>

<div class="counter-container">
  <input class="quantity-input" id="x_3" type="text" value="1">
  <div class="btn-container">
    <button id="y_3" class="btn-arrow increment">▲</button>
    <button id="z_3" class="btn-arrow drecement">▼</button>
  </div>
</div>