在下面的代码中,我将gobal变量“myDiv”分配给一个jQuery元素。但是然后在“test()”函数中,似乎myDiv变量已声明但未定义。我必须重新分配$('myDiv'),然后才能对它做任何事情。使用javascript模块模式的jQuery变量范围
伪造变量XYZ似乎到达就好了,但...
<!DOCTYPE html>
<htm>
<head>
<title>Javascript Test Code</title>
<script src="js/jquery-1.9.0.min.js"></script>
<script>
var App = App || (function() {
var myDiv = $('#myDiv'), // define a global jQuery element variable.
xyz = 'xyz'; // and a bogus variable as a test.
function test()
{
console.log('running test...','myDiv is', myDiv); // length is 0
console.log('xyz is ', xyz); // says xyz
myDiv = $('#myDiv'); // after selecting with jQuery...
console.log('running test...','myDiv is', myDiv); //length is 1
console.log('xyz is ', xyz); // still says xyz
}
return {test:test}
}());
$(function(){
App.test();
});
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
这与范围界定无关,变量存在且其值正确记录。对于这个问题,请参阅重复[为什么jQuery或DOM方法(如\'getElementById \'找不到该元素?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a -dom-method-such-as-getelementbyid-not-find-the-element) – Bergi 2013-02-21 00:51:42