onclick 定义的方法 在$(function(){})或window.onload=function(){}中无效

写在$(function(){ }) 或 window.onload=function(){} 里面的函数是处在一个局部作用域中的,也就是我们常说的“闭包”,只能由同处在一个闭包内的代码访问到。

如下:onclick="showAlert()"方法无效 可以写在window.onload=function(){} 或$(function(){ }) 外,或使用

document.getElementById('click').onclick=function(){},在jquery中使用$("#click").click(function(){})解决;
 
 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div  onclick="alert(111)">弹框1</div>
        <!-- showAlert is not defined -->
        <div  onclick="showAlert()">弹框2</div>
        
        <div id="click">弹框3</div>
    </body>
</html>
<script>
    window.onload=function(){
        function showAlert(){
            alert(222);
        }
        document.getElementById('click').onclick=function(){
            alert(333);
        }
    }    
</script>
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/zhouyuxiang/p/12612745.html