以下两个代码段均有效:
在js文件中使用IIFE:
(function initialize() {
txtInput = document.getElementById('txtInput');
txtResult = document.getElementById('txtResult');
txtInput.value = "0";
txtResult.value = "0";
}());
Run Code Online (Sandbox Code Playgroud)
在html文件中调用window加载事件的initialize():
window.addEventListener('load', initialize, false);
Run Code Online (Sandbox Code Playgroud)
是一种比其他更好的方法; 在表现还是其他方面?就目前而言,我更倾向于向窗口对象添加事件监听器,因为它更具可读性.