html 数量加减 代码
时间: 2023-05-30 21:03:55 浏览: 77
以下是一个简单的 HTML 数量加减代码示例:
```
<div>
<button onclick="decrease()">-</button>
<input type="text" id="quantity" value="1">
<button onclick="increase()">+</button>
</div>
<script>
function decrease() {
var quantityField = document.getElementById("quantity");
var quantity = parseInt(quantityField.value);
if (quantity > 1) {
quantityField.value = quantity - 1;
}
}
function increase() {
var quantityField = document.getElementById("quantity");
var quantity = parseInt(quantityField.value);
quantityField.value = quantity + 1;
}
</script>
```
这段代码包含一个包含减号、数量输入框和加号的 div 元素。点击减号按钮将减少数量输入框中的数量,点击加号按钮将增加数量输入框中的数量。在 JavaScript 中,我们使用 `getElementById` 方法获取数量输入框元素,然后通过 `value` 属性获取或设置输入框的当前值。在减少功能中,我们检查当前数量是否大于 1,以防止用户将数量减少到负数。在增加功能中,我们只需将当前数量增加 1。