需求:用户点击加号,则文本框+1,点击减号,则文本框-1,如果文本框为1,则禁用减号
JavaScript
点击事件监听
全部源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
width: 80px;
}
input[type=text] {
width: 50px;
height: 44px;
outline: none;
border: 1px solid #ccc;
text-align: center;
border-right: 0;
}
input[type=button] {
height: 24px;
width: 22px;
cursor: pointer;
}
input {
float: left;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div>
<input type="text" id="total" value="1" readonly>
<input type="button" value="+" id="add">
<input type="button" value="-" id="reduce" disabled>
</div>
<script>
// 获取标签
let total = document.querySelector('#total');
let add = document.querySelector('#add');
let reduce = document.querySelector('#reduce');
// 定义变量
let num = 1;
// 绑定事件
add.addEventListener('click', function () {
num++;
// 把变量给total
// input的更改值要是value
total.value = num;
// 取消禁用减号按钮
reduce.disabled = false;
});
reduce.addEventListener('click', function () {
num--;
// 当num等于1的时候禁用按钮
if (num === 1) {
reduce.disabled = true;
}
// 把变量赋给total
total.value = num;
});
</script>
</body>
</html>