首页 > 解决方案 > 加/减数量字段

问题描述

我正在尝试在我的 4 种不同的产品模式上实现加法/减法功能。它具有以下相同的类名。

<div class="input-group">
    <span class="input-group-btn">
        <button class="btn btn-default btn-subtract" type="button">-</button>
    </span>
    <input type="text" class="form-control no-padding text-center item-quantity" value="1">
    <span class="input-group-btn">
         <button class="btn btn-default btn-add" type="button">+</button>
    </span>
</div>

这是我的 JS。

var minus = document.querySelector("btn-subtract")
var add = document.querySelector("btn-add");
var quantityNumber = document.querySelector("item-quantity");
var currentValue = 1;

minus.addEventListener("click", function(){
    currentValue -= 1;
    quantityNumber.textContent = currentValue;
    console.log(currentValue)
});

add.addEventListener("click", function() {
    currentValue += 1;
    quantityNumber.textContent = currentValue;
    console.log(currentValue);
});

但是,它在输入字段中没有显示任何内容。有什么建议吗?

标签: javascripthtml

解决方案


问题是您的选择器很糟糕,您不能在输入字段上使用 textContent 属性来更改其值。下面的代码应该可以解决问题:

var minus = document.querySelector(".btn-subtract")
var add = document.querySelector(".btn-add");
var quantityNumber = document.querySelector(".item-quantity");
var currentValue = 1;

minus.addEventListener("click", function(){
    currentValue -= 1;
    quantityNumber.value = currentValue;
    console.log(currentValue)
});

add.addEventListener("click", function() {
    currentValue += 1;
    quantityNumber.value = currentValue;
    console.log(currentValue);
});

推荐阅读