在下面的代码中,我为 gobal 变量“myDiv”分配了一个 jQuery 元素。但是在“test()”函数内部,似乎 myDiv 变量已声明但未定义。在我可以对它做任何事情之前,我必须再次重新分配它 $('myDiv') 。
Bogus 变量 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>