我有一组生成的输入,其任务是将商品添加到商店列表并将值添加到sessionStorage密钥:
$('.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>
问题是我还要更改其他生成的输入:
如何仅更改我单击的输入?
答案 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>