基于这个video,为什么click事件会影响数组的其他索引? 我尝试使用 .eq() 、 .index() 并将 id 更改为 class 选择器,但是如何操作?也许我做错了什么?
对于每个:
@foreach ($keranjang as $row)
<table class="table table-bordered" style="border-width:6px">
<thead class="thead-dark">
<tr>
...
</tr>
</thead>
<tbody>
<tr>
...
<td>
<button onclick="this.parentNode.querySelector('#qty').stepDown()" class="min-btn" style="width: 20px">-</button>
<input readonly class="qty" id="qty" style="width: 30px; text-align:center" type="number"
name="qty" value="{{$row->qty}}">
<button onclick="this.parentNode.querySelector('#qty').stepUp()" class="plus-btn" style="width: 20px">+</button>
</td>
...
</tr>
</tbody>
</table>
@endforeach
Jquery:
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('.qty').attr('min',1);
$('.qty').attr('max',5);
$('.min-btn').on('click', function() {
$('.plus-btn').attr('disabled', false);
if ($('.qty').val() == 1)
{
$(this).attr('disabled', true);
}
});
$('.plus-btn').on('click', function() {
$('.min-btn').attr('disabled', false);
if ($('.qty').val() == 5)
{
$(this).attr('disabled', true);
}
});
});
</script>
$('.plus-btn') $('.qty')
这些选择器针对多个 DOM 元素,这可能不是您想要的。您想要确定其范围并定位本地加号和减号按钮。
$(document).ready(function() {
$('.qty').attr('min',1);
$('.qty').attr('max',5);
$('.min-btn').on('click', function() {
const $this = $(this);
const $td = $this.closest("td");
const $input = $td.find('.qty');
$td.find('.plus-btn').attr('disabled', false);
if($input.val() == 1){
$this.attr('disabled', true);
}
});
$('.plus-btn').on('click', function() {
const $this = $(this);
const $td = $this.closest("td");
const $input = $td.find('.qty');
$td.find('.min-btn').attr('disabled', false);
if($input.val() == 5){
$this.attr('disabled', true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table class="table table-bordered" style="border-width:6px">
<thead class="thead-dark">
<tr>
...
</tr>
</thead>
<tbody>
<tr>
...
<td>
<button onclick="this.parentNode.querySelector('#qty').stepDown()" class="min-btn" style="width: 20px">-</button>
<input readonly class="qty" id="qty" style="width: 30px; text-align:center" type="number"
name="qty" value="0">
<button onclick="this.parentNode.querySelector('#qty').stepUp()" class="plus-btn" style="width: 20px">+</button>
</td>
<td>
<button onclick="this.parentNode.querySelector('#qty').stepDown()" class="min-btn" style="width: 20px">-</button>
<input readonly class="qty" id="qty" style="width: 30px; text-align:center" type="number"
name="qty" value="1">
<button onclick="this.parentNode.querySelector('#qty').stepUp()" class="plus-btn" style="width: 20px">+</button>
</td>
...
</tr>
</tbody>
</table>