html-如何让这个javascript函数一直工作?(未捕获的TypeError:无法读取null的属性)
我正在尝试创建两个数字输入,每个输入都有自己的自定义“+”和“-”按钮。但是,使用我当前的代码,按钮功能似乎只在某些时候起作用。在其他情况下,我得到一个Uncaught TypeError: Cannot read properties of null (reading 'value') at HTMLButtonElement.<anonymous>错误。
这是 HTML:
<div class="col">
<div class="row">
<div class="input-group mx-auto w-50">
<div class="input-group-prepend">
<button class="btn btn-dark btn-sm minus" data-id="one"
type="button"><i class="fa fa-minus"></i></button>
</div>
<input type="number" id="one"
class="form-control form-control-sm text-center" value="0">
<div class="input-group-prepend">
<button class="btn btn-dark btn-sm plus" data-id="one" type="button"><i
class="fa fa-plus"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="input-group mx-auto w-50">
<div class="input-group-prepend">
<button class="btn btn-dark btn-sm minus" data-id="two"
type="button"><i class="fa fa-minus"></i></button>
</div>
<input type="number" id="two"
class="form-control form-control-sm text-center" value="0">
<div class="input-group-prepend">
<button class="btn btn-dark btn-sm plus" data-id="two" type="button"><i
class="fa fa-plus"></i></button>
</div>
</div>
</div>
</div>
这是Javascript:
<script>
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll('.minus').forEach(item => {
item.addEventListener('click', event => {
var input_id = event.target.getAttribute('data-id')
console.log('Minus button clicked for input ' + input_id)
var quantityInput = document.getElementById(input_id);
var currentQuantity = parseInt(quantityInput.value);
quantityInput.value = currentQuantity - 1
})
})
document.querySelectorAll('.plus').forEach(item => {
item.addEventListener('click', event => {
var input_id = event.target.getAttribute('data-id')
console.log('Plus button clicked for input ' + input_id)
var quantityInput = document.getElementById(input_id);
var currentQuantity = parseInt(quantityInput.value);
quantityInput.value = currentQuantity + 1
})
})
})