JavaScript通过dom操作实现简单的购物加减
前言
本博客仅限于通过写简单的JavaScript购物加减小操作熟悉JavaScript的dom操纵,查找元素功能
实现步骤
1.写出html骨架
代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<span><button id = "reduce_b">-</button></span>
<span id ="count">0</span>
<span><button id = "add_b">+</button></span>
</div>
</body>
</html>
实现效果:
2.通过document定位获取数值信息
var num = document.getElementById("count")
3.写增加减少函数
<script>
var num = document.getElementById("count")
var add = function(){
if(num.innerText>=10){
alert("不能再加了,已经满了")
}else{
num.innerText++
}
}
var reduce = function(){
if(num.innerText<=0){
alert("不能再减了,已经到底了")
}else{
num.innerText--
}
}
</script>
4.将函数加入点击事件
<div>
<span><button id = "reduce_b" onclick="reduce()">-</button></span>
<span id ="count">0</span>
<span><button id = "add_b" onclick="add()">+</button></span>
</div>
总结
本文仅通过document的id定位,并通过给按钮的时间添加函数实现,属于是使用工具和熟悉方法的过程
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<span><button id = "reduce_b" onclick="reduce()">-</button></span>
<span id ="count">0</span>
<span><button id = "add_b" onclick="add()">+</button></span>
</div>
<script>
var num = document.getElementById("count")
var add = function(){
if(num.innerText>=10){
alert("不能再加了,已经满了")
}else{
num.innerText++
}
}
var reduce = function(){
if(num.innerText<=0){
alert("不能再减了,已经到底了")
}else{
num.innerText--
}
}
</script>
</body>
</html>