我一直在研究揭示模块模式。我最初开始使用单例模式,但通过阅读模块模式似乎是更好的选择。
所以我测试了以下内容:
var test = (function() {
var init = function () {
alert('hello');
};
return {
init: init
};
})();
这在调用时工作正常
<script>test.init();</script>
但是,我想使用 jQuery,所以我尝试了:
var test = (function($) {
var init = function () {
$("#samplediv").html('test');
alert('hello');
};
return {
init: init
};
})(jQuery);
但这行不通。它在使用时确实有效:
<script>$(function() { test.init(); });</script>
调用时如何在不添加 jQuery 的情况下让它工作?
最佳答案
通常,任何涉及 DOM 的事情都需要在 $(document).ready(fn)
回调中完成。 $(fn)
是这个的快捷方式。
所以它不起作用的原因是因为您正在搜索尚不存在的 DOM 元素。所以你有2个选择。要么您必须使用 $()
包装器,要么找到另一种方法来仅在 DOM 元素存在后运行您的代码。另一种方法是将脚本标记移动到 body 标记的底部,以便 DOM 元素在运行时可以存在。
<body>
<!-- your page elements here -->
<script>test.init();</script>
</body>
关于javascript - 使用 jQuery 显示模块模式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8334797/