gpt4 book ai didi

javascript - 我怎样才能让这个javascript函数一直工作? (未捕获类型错误 : Cannot read properties of null)

转载 作者:行者123 更新时间:2023-12-05 03:21:16 24 4
gpt4 key购买 nike

我正在尝试创建两个数字输入,每个输入都有自己的自定义“+”和“-”按钮。但是,根据我当前的代码,按钮功能似乎只在某些时候有效。在其他情况下,我得到一个 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
})
})
})

这是点击几个按钮后的输出示例:

Sample output after clicking a few buttons

最佳答案

event.target 可能是按钮内部的 span,因此代码可能找不到 data-id 属性。取而代之的可能是在不使用 event.target 的情况下获取 id。使用 itemevent.currentTarget

关于javascript - 我怎样才能让这个javascript函数一直工作? (未捕获类型错误 : Cannot read properties of null),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73016183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com