javascript - 加/减数量字段
问题描述
我正在尝试在我的 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);
});
但是,它在输入字段中没有显示任何内容。有什么建议吗?
解决方案
问题是您的选择器很糟糕,您不能在输入字段上使用 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);
});
推荐阅读
- .net - 将我的站点部署到生产 RedirectToAction 时显示空白页
- microsoft-graph-api - Microsoft Graph API 将附件添加到另一条消息中的消息
- vba - VBA 加密方式
- python - Tkinter 中的图像
- c++ - 为什么库 API + 编译器 ABI 足以保证不同版本 gcc 的对象之间的兼容性?
- ruby-on-rails - 将关联嵌入到 ActiveRecord 模型中
- reactjs - 在 React 中导出异步函数的结果
- c++ - 动态创建的复选框的事件处理程序
- ruby-on-rails - Rails 中嵌套和浅层资源的 URL 生成错误
- python - Python 中的分类数据:ValueError:无法将字符串转换为浮点数: