为了账号安全,请及时绑定邮箱和手机立即绑定

谁能解释下下面这段代码的错误

谁能解释下下面这段代码的错误

清风流光 2017-04-16 05:27:42
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> .red { width: 100px; height: 100px; background: red; } .blue { width: 100px; height: 100px; background: blue; } </style> <script> window.onload = function() { var box = document.getElementById('box'); box.onclick = toBlue(); } function toRed() { this.className = 'red' this.onclick = toBlue() } function toBlue() { this.className = 'blue' this.onclick = toRed() } </script> </head> <body> <div id='box' class="red" style="text-align: center;line-height: 100px;">DIV</div> <body/> </html>为什么事件在函数里调用必须等于函数 在函数里调用值没有执行事件操作 为什么事件还是会自动执行?
查看完整描述

3 回答

已采纳
?
ruibin

TA贡献358条经验 获得超213个赞

 window.onload = function() {

                var box = document.getElementById('box');

                box.onclick = toBlue();

                //这是mark1

            }

 

请看这段代码。这段代码的意思是页面一加载完成就执行下面的js代码。那么当js代码执行到mark1的时候发生了什么呢?

会执行toBlue。为什么?因为toBlue()。这是你写的。这得意思是调用toBlue然后把toBlue的结果赋值给box.onclick。所以不管执行不执行时间,toBlue一定会执行,因为js代码运行到这一行了! 就是这么简单,这和事件还扯不上关系~

查看完整回答
3 反对 回复 2017-04-16
?
西兰花伟大炮

TA贡献376条经验 获得超318个赞

<!DOCTYPE html>
<html>
 <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .red {
                width: 100px;
                height: 100px;
                background: red;
            }
             
            .blue {
                width: 100px;
                height: 100px;
                background: blue;
            }
        </style>
        <script>
            window.onload = function() {
                var box = document.getElementById('box');
                box.onclick = toBlue;
            }
 
            function toRed() {
                this.className = 'red'
                this.onclick = toBlue;
            }
 
            function toBlue() {
                this.className = 'blue'
                this.onclick = toRed;
            }
        </script>
    </head>
 
    <body>
        <div id='box' class="red" style="text-align: center;line-height: 100px;">DIV</div>
        <body/>
 
</html>

不要加上括号

查看完整回答
2 反对 回复 2017-04-16
?
落叶1111

TA贡献57条经验 获得超9个赞

X.onclick=function(){};是自调用函数

查看完整回答
1 反对 回复 2017-04-16
?
slumdog

TA贡献6条经验 获得超4个赞

最后的body结束标签难道不应该是</body>吗?

查看完整回答
1 反对 回复 2017-04-16
  • 3 回答
  • 0 关注
  • 1536 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信