将文档对象传递给函数

Pass document object to function

本文关键字:函数 文档 对象      更新时间:2023-09-26

我有一个按照模块模式编写的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(){};
        }
    }
}

如何通过文档对象传递UI操作?

P/S:我收到以下错误:

Cannot read property 'addEventListener' of null

是因为我无法从 makeUI 操作访问文档吗?

.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 元素就位。 请参阅这个答案,纯JavaScript等同于jQuery的$.ready()如何在页面/dom准备好时调用函数以获取更多详细信息。