点击事件单独调用每一个函数都没问题,但是写上循环体之后就不行了。函数单独来说没问题,我都是写一个测试一个,然后点击事件单独的函数也能显示但是有循环体就有问题了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{padding:0;margin: 0;}
#btn{position: absolute;top:0;left:300px;}
p{width: 50px;height:50px;position: absolute;top:0;left:0;background:green;font-size: 30px; text-align:center;color:red;line-height: 50px;cursor: pointer;}
</style>
<script>
window.onload=function () {
var btn = document.getElementById("btn");
var op = document.getElementsByTagName("p");
function first() {
{
// btn.style.display = "none";
for (var i = 0; i < 5; i++) {
document.body.innerHTML += '<p>' + i + '</p>';
}
for (i = 0; i < op.length; i++) {
//op[i].index = i;
if (i > op.length / 2) {
op[i].style.left = i * 60 + "px";
op[i].style.top = (i - parseInt(op.length / 2)) * 60 + "px";
}
else {
// alert(i);
op[i].style.top = (parseInt(op.length / 2) - i) * 60 + "px";
op[i].style.left = i * 60 + "px";
}
}
}
}
function second() {
// btn.style.display="none";
for (var i = 0; i < 5; i++) {
document.box2.innerHTML += '<p id="box">' + i + '</p>';
}
for ( i = 0; i < op.length; i++) {
//op[i].index = i;
if(i>op.length/2){
op[i].style.left = (op.length-i -1)* 60 + "px";
op[i].style.top=i*60+"px";
}
else {
// alert( i);
op[i].style.top = i* 60 + "px";
op[i].style.left = i * 60 + "px";
}
}
}
function three() {
//btn.style.display = "none";
for (var i = 0; i < 5; i++) {
document.body.innerHTML += '<p>' + i + '</p>';
}
for (i = 0; i < op.length; i++) {
//op[i].index = i;
if (i > op.length / 2) {
op[i].style.left = (i - parseInt(op.length / 2)) * 60 + "px";
op[i].style.top = i * 60 + "px";
}
else {
// alert( i);
op[i].style.top = i * 60 + "px";
op[i].style.left = ( parseInt(op.length / 2) - i) * 60 + "px";
}
}
}
function four() {
//btn.style.display="none";
for (var i = 0; i < 5; i++) {
document.body.innerHTML += '<p>' + i +'</p>';
}
for ( i = 0; i < op.length; i++) {
op[i].index = i;
if(i>op.length/2){
op[i].style.left = i * 60 + "px";
op[i].style.top=(op.length-i-1)*60+"px";
}
else {
op[i].style.top = i * 60 + "px";
op[i].style.left = i * 60 + "px";
}
}
}
var k=0;
btn.onclick = function () {
//if(k==0){alert(1)}
if(k==0){first()}
if(k==1){second()}
if(k==2){three()}
if(k==3){four()}
k++;
// first();
//second();
//three();
//four();
}
};
</script>
</head>
<body>
<input id="btn" type="button" value="点击生成li"/>
</body>
</html>
document.body.innerHTML += '<p>' + i + '</p>';这一句导致的,因为你重新innerHTML之后,之前绑定的onclick没有了,所有其实就执行一次k==0的情况而已