javascript - 關(guān)于函數(shù)調(diào)用的問題,點(diǎn)擊事件的循環(huán)體不能循環(huán)這四個(gè)函數(shù),但是用alert測(cè)試過循環(huán)體能循環(huán)。
問題描述
點(diǎn)擊事件單獨(dú)調(diào)用每一個(gè)函數(shù)都沒問題,但是寫上循環(huán)體之后就不行了。函數(shù)單獨(dú)來說沒問題,我都是寫一個(gè)測(cè)試一個(gè),然后點(diǎn)擊事件單獨(dú)的函數(shù)也能顯示但是有循環(huán)體就有問題了。<!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 type='button' value='點(diǎn)擊生成li'/></body></html>
問題解答
回答1:document.body.innerHTML += ’<p>’ + i + ’</p>’;這一句導(dǎo)致的,因?yàn)槟阒匦耰nnerHTML之后,之前綁定的onclick沒有了,所有其實(shí)就執(zhí)行一次k==0的情況而已
