我试图在没有全局变量的情况下使用windows.load。
HTML代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="main.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
Name: <input type="text" id="txt1"><br><br>
<input type="button" value="Check Input" id="b1">
</form>
</body>
</html>
&#13;
JavaScript全局变量代码:
/*jslint browser: true*/
var myButton;
window.onload = function () {
"use strict";
myButton = document.getElementById("b1");
myButton.addEventListener("click",alertMM);
};
function alertMM() {
"use strict";
window.console.log(myButton.value);
}
&#13;
最后没有全局变量代码的NOT WORKING:
/*jslint browser: true*/
var myNS = {
myButton: undefined,
//
setUp: function () {
"use strict";
myNS.myButton = document.getElementById("b1");
myNS.myButton.addEventListener("click", alertMM);
}
};
window.onload = myNS.setUp();
function alertMM() {
"use strict";
window.console.log(myNS.myButton.value);
}
&#13;
我想停止使用全局变量的原因是我担心它会与未来的代码冲突。
提前致谢
阿德里安
答案 0 :(得分:5)
在:
window.onload = myNS.setUp();
当您定义window.onload
回调时,您应该为其分配函数本身(仅myNS.setUp
),以便稍后调用它。你的代码所做的是立即调用函数并分配结果。
答案 1 :(得分:0)
JavaScript中的变量作用域主要是面向函数作用域。在中,函数包含它们的内部变量。因此,您可以通过在您分配给window.onload
的函数中声明变量(并分配DOM el)来避免污染全局范围:
window.onload = function() {
//variable assignments inside the function
var button1 = document.getElementById('b1');
var button2 = document.getElementById('globalCheck');
//anonymous functions attached instead of named functions
button1.addEventListener('click', function() {
alert(button1.value);
});
button2.addEventListener('click', function() {
alert("var button1 in the global scope: " + window.button1 + "\n" + "var button2 in the global scope: " + window.button2);
});
};
&#13;
.greyButton {
background-color: grey;
color: #f5f5f5;
width: 30%;
}
#txt1 {
width: 29%;
}
&#13;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="main.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
<div>
<input type="text" id="txt1" placeholder="Name" value="">
<br>
<input type="button" value="Check Input" id="b1" class="greyButton">
</div>
<br>
<div>
<input type="button" value="Are the variables global?" id="globalCheck" class="greyButton">
</div>
</form>
</body>
</html>
&#13;