我有一个按照模块模式编写的 JavaScript 代码:
var controller = function () {
return {
init: function() {
// settings and initialization
}
makeUIactions: function() {
//set UI actions, for example callback function of a button:
document.getElementById("ShuffleButton").addEventListener("click", Shuffle);
function Shuffle(){};
}
}
}
如何将文档对象传递给 makeUIactions?
P/S:我收到以下错误:
Cannot read property 'addEventListener' of null
是因为我无法从 makeUIactions 访问文档吗?
HTML:
<script>
controller.init();
controller.makeUIactions();
</script>
<div>
<input type="button" id="ShuffleButton" style="margin-top:20px" value="Shuffle" data-inline="true">
<input type="button" id="SubmitButton" style="margin-top:20px" value="Submit" data-inline="true">
</div>
最佳答案
您的代码在 DOM 加载之前运行,document.getElementById("ShuffleButton")
找不到 DOM 元素,因此返回 null
。当您尝试null.addEventListener()
时,它会抛出您看到的错误。
您可以通过移动以下内容来修复它:
<script>
controller.init();
controller.makeUIactions();
</script>
就在您的 </body>
之前标签,以便 DOM 元素在脚本运行之前就位。请参阅此答案 pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it了解更多详细信息。
关于javascript - 将文档对象传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28935580/