js实现开关灯 开关灯执行一次后,就不能执行了

img


var btn=document.querySelector('button')
            var body=document.querySelector('body')
            var i=1
            btn.onclick=function(){
                  if(i==1){
                   body.style.backgroundColor='white'
                   console.log(body)
                   btn.innerHTML='关灯'
                   i=0
                  }else{
                   body.style.backgroundColor='gray'
                   btn.innerHTML='开灯'
                   i=1
                  }
            }

img


你在else的时候把按钮清除了啊,整个body就两个文字了,你的点击事件又绑定在按钮上的,肯定不可以啊!

楼上已经说了 我大概说一下问题在那
你的else方法体内把body给innerHTML了,导致按钮丢失 而你写进去的字符串并无点击事件

亲测可用,如有帮助请点采纳

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
 <button type='button”class='btn”>开火</button>
 

</body>
<script type="text/javascript">
     
var btn=document.querySelector('button')
            var body=document.querySelector('body')
            var i=1
            btn.onclick=function(){
                  if(i==1){
                   body.style.backgroundColor='white'
                   console.log(body)
                   btn.innerHTML='关灯'
                   i=0
                  }else{
                   body.style.backgroundColor='gray'
                   btn.innerHTML='开灯'
                   i=1
                  }
            }
</script>
</html>