1.将按钮点击事件写在js外面,拿到按钮后,处理点击事件操作。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
</style>
</head>
<body>
![](image/icon_01.png)
<p></p>
<button class="pre" onclick="pre();">上一张</button>
<button class="next" onclick="next();">下一张</button>
<!--<script src="js/index.js"></script>-->
<script type="text/javascript">
// 拿到所有的标签
var icon = document.getElementsByClassName('icon')[0];
var maxImgCount = 9;
var minImgCount = 1;
var currentImg = minImgCount;
// 点击上一张
function pre(){
if(currentImg == minImgCount){
currentImg = maxImgCount;
}else{
currentImg = currentImg - 1;
}
icon.src = "image/icon_0" + currentImg + ".png"
}
// 点击下一张
function next(){
if(currentImg == maxImgCount){
currentImg = minImgCount;
}else{
currentImg = currentImg + 1;
}
icon.src = "image/icon_0" + currentImg + ".png"
}
</script>
</body>
</html>
2.将按钮点击事件在js里面直接赋值。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
</style>
</head>
<body>
![](image/icon_01.png)
<p></p>
<button class="pre">上一张</button>
<button class="next">下一张</button>
<!--<script src="js/index.js"></script>-->
<script type="text/javascript">
// 拿到所有的标签
var icon = document.getElementsByClassName('icon')[0];
var button1 = document.getElementsByClassName('pre')[0];
var button2 = document.getElementsByClassName('next')[0];
var maxImgCount = 9;
var minImgCount = 1;
var currentImg = minImgCount;
// 点击上一张
button1.onclick = function pre(){
if(currentImg == minImgCount){
currentImg = maxImgCount;
}else{
currentImg = currentImg - 1;
}
icon.src = "image/icon_0" + currentImg + ".png"
}
// 点击下一张
button2.onclick = function next(){
if(currentImg == maxImgCount){
currentImg = minImgCount;
}else{
currentImg = currentImg + 1;
}
icon.src = "image/icon_0" + currentImg + ".png"
}
</script>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
alert('加载完毕');
}
</script>
<script type="text/javascript">
window.onunload = function(){
alert('退出');
}
</script>