先看下例子
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-1.10.2_d88366fd.js"></script>
</head>
<body>
<script>
$(function(){
function console1(){
console.log('js1:console1');
}
})
</script>
<script>
$(function(){
console1();
})
</script>
</body>
</html>
这样写 console1函数无法执行报错,说没找到console1函数。
想了半天,原来每个$(function(){})都是一个函数,函数都有自己的作用域,匿名函数相当于私有的函数,要把匿名函数改成 全局函数就可以在下面用了。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery-1.10.2_d88366fd.js"></script>
</head>
<body>
<script>
var console1;
$(function(){
console1=function (){
console.log('js1:console1');
}
})
</script>
<script>
$(function(){
console1();
})
</script>
</body>
</html>