JavaScript 我弄了俩盒子,用了一个 事件 function ,怎么第二个找不到 function ?


<script type="text/javascript">
    $(document).ready(function(){    /***加载事件的开始,这行就不别改了!**/

        document.getElementById("one").onmouseenter=show;
        
        function show()
        {console.log( '********' );}

    })    /***加载事件的结束,这行就不别改了!**/
</script>



<body>

   <div id="one"></div>

   <div onmouseenter="show()" id="two" ></div> //★★就是这个地方,提示:"Uncaught ReferenceError: show is not defined"
<body>

就是★★的地方,提示:"Uncaught ReferenceError: show is not defined"

我要是把
$(document).ready(function(){    /***加载事件的开始,这行就不别改了!**/ 
删了,第一个 <div> 又不管事了...
阅读 3.1k
3 个回答

楼主应该这样写吧

function show(){
    console.log( '********' );
}
$(document).ready(function(){   
    
    document.getElementById("one").onmouseenter=show;

})    

如果你定义在reday里面的function实际上这是一个私有作用域,show只能在function() {}里面使用;而two绑定的函数必须是在全局中可以调用到。

show的作用域不对:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){    /***加载事件的开始,这行就不别改了!**/
    
            document.getElementById("one").onmouseenter=show;
            
            window.show = function(){console.log( '********' );};

        })
    </script>
    <style>div{width:100px;height:100px;background-color:red;margin:0 auto;}</style>
</head>

<body>

   <div id="one"></div>

   <div onmouseenter="show()" id="two" ></div>
</body>
</html>

楼主请参考楼上的两种处理方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题