简体   繁体   English

用jQuery揭示模块模式不起作用

[英]Revealing module pattern with jQuery not working

I've been playing around with the revealing module patter. 我一直在玩弄暴露的模块模式。 I originally started using the Singleton pattern but from reading around the module pattern seems to be the better option. 我最初开始使用Singleton模式,但从模块模式阅读似乎是更好的选择。

So i've tested the following: 所以我测试了以下内容:

var test = (function() {

var init = function () {
    alert('hello');
};

return {
    init: init
};
})();

and this works fine when calling 这在调用时工作正常

<script>test.init();</script>

However, i want to use jQuery so i tried: 但是,我想使用jQuery所以我试过:

var test = (function($) {

var init = function () {
    $("#samplediv").html('test');
    alert('hello');
};

return {
    init: init
};
})(jQuery);

but this doesn't work. 但这不起作用。 It does work when using: 使用时它确实有效:

<script>$(function() { test.init(); });</script>

How can i get it to work without the added jQuery when calling it? 如何在没有添加jQuery的情况下让它工作?

Usually, anything that touches the DOM needs to done in the $(document).ready(fn) callback. 通常,任何触及DOM的东西都需要在$(document).ready(fn)回调中完成。 $(fn) is a shortcut for this. $(fn)是此的快捷方式。

So the reason it doesn't work is because you are searching for DOM elements that don't exist yet. 所以它不起作用的原因是因为你正在搜索尚不存在的DOM元素。 So you have 2 choices. 所以你有2个选择。 Either you must use the $() wrapper, or find another way to run your code only after the DOM elements exist. 您必须使用$()包装器,或者只在DOM元素存在后才能找到另一种方法来运行代码。 Another way to do this is to move your script tag the bottom of the body tag so that the DOM elements can exist when it's ran. 另一种方法是将脚本标记移动到body标记的底部,以便DOM元素在运行时可以存在。

<body>
  <!-- your page elements here -->
  <script>test.init();</script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM