2016-01-16 26 views
0

我做一个无限的游戏,我想算clickings。我尝试了一切,但都没有奏效。我是编程的首选,但我现在喜欢它。请有人帮助我!这是代码(2两件事:1.对不起,我的英文不好,我想最好的方式复制代码2.但这并不表明寄托都):HTML按钮命中计数

<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
     <style type=text/css> 
      .button { 
       background-color: red; 
       float: center; 
       width: 200px; 
       height: 200px; 
       margin-left: auto; 
       margin-right: auto; 
       display: block; 
       margin-top: 300px; 
       margin-bottom: 0%; 
      } 

      .body { 
       background-color: yellow; 
      } 

     </style> 
    </head> 

    <body class="body" id="body"> 
     <button onclick="myFunction()" class="button" style="font-size:50px" ; id="gomb">Nyomj meg!</button> 
     <script> 
      var count = 0; 
      var a = true; 
      var gomb = document.getElementById("gomb"); 
      var body = document.getElementById("body"); 

      gomb.onclick = function() { 
       if (a == true) { 
        gomb.style.background = "yellow"; 
        gomb.innerHTML = "Na még egyszer!"; 
        body.style.background = "red"; 
        a = false; 
       } else { 
        gomb.style.background = "red"; 
        body.style.background = "yellow"; 
        a = true; 
       } 
      }; 

      function myFunction() { 
       if (count == 5) { 
        gomb.style.display = "none" 
       } else { 
        count = count + 1; 
       }; 
      } 
     </script> 
    </body> 
</html> 
+0

那么是什么问题,是不是正在显示的计?计数不正确递增?你期望的结果是什么? – Andrew

回答

0

尝试更改代码:

window.addEventListener:这有助于您重新安排代码,以便在加载页面时分配事件点击和变量。

使用的addEventListener附加一个事件到HTML元素

这是unusefull给一个id和名称的身体。

var count = 0; 
 
var a = true; 
 
var gomb; 
 
var body; 
 

 
window.addEventListener('load', function(e) { 
 
    gomb = document.getElementById("gomb"); 
 
    body = document.getElementsByTagName('body')[0]; 
 

 
    gomb.addEventListener('click', function(e) { 
 
    if (a==true){ 
 
     gomb.style.background = "yellow"; 
 
     gomb.innerHTML="Na még egyszer!"; 
 
     body.style.background = "red"; 
 
     a = false; 
 
    } 
 
    else 
 
    { 
 
     gomb.style.background = "red"; 
 
     body.style.background = "yellow"; 
 
     a = true; 
 
    } 
 
    }); 
 
}); 
 

 
function myFunction(){ 
 
    if(count==5) { 
 
    gomb.style.display="none" 
 
    } 
 
    else 
 
    { 
 
    count=count+1; 
 
    }; 
 
}
.button{ 
 
    background-color:red; 
 
    float: center; 
 
    width: 200px; 
 
    height: 200px; 
 
    margin-left:auto; 
 
    margin-right:auto; 
 
    display:block; 
 
    margin-top:300px; 
 
    margin-bottom:0%; 
 
} 
 
body{ 
 
    background-color: yellow; 
 
}
<button onclick="myFunction()" class="button" style="font-size:50px"; id="gomb">Nyomj meg!</button>