[英]Module variable can't be initiated with DOM elements
I'm trying to keep my Javascript code inside of modules, but I am not being able to initialize the module's variables with DOM elements. 我试图将Javascript代码保留在模块中,但无法使用DOM元素初始化模块的变量。 Everything I have tried have only returned empty variables. 我尝试过的一切都只返回了空变量。
<html>
<head>
<script type="text/javascript" src="myModule.js"></script>
</head>
<body>
<div id="baner"></div>
/* bunch of HTML here */
<script type="text/javascript">
$(document).ready(function(){
myModule.init();
});
</script>
</body>
</html>
And my Javascript code looks like this: 我的Javascript代码如下所示:
var myModule = (function(){
var banerSegment;
var init = function(){
//Inicializar variáveis relacionadas ao DOM
banerSegment = $('#baner');
};
return {
init: init,
baner: banerSegment
};
})();
The way I see it, I thought that after the DOM was ready, the myModule.init()
function would be called and this function would populate the variable banerSegment
with the contents of the DOM element. 我的看法是,我认为在DOM准备就绪后,将myModule.init()
函数,并且此函数将使用DOM元素的内容填充变量banerSegment
。 But I only get undefined from calling myModule.baner
. 但是我只能通过调用myModule.baner
获得未定义的myModule.baner
。
Why am I missing here? 为什么我想念这里?
Thanks in advance! 提前致谢!
While this is a good start, I don't think you've quite grasped the module pattern yet. 尽管这是一个好的开始,但我认为您还没有完全掌握模块模式。 I would suggest checking out Todd Motto's guide here 我建议在这里查看Todd Motto的指南
I think the cleanest solution would be using this
like so: 我认为干净的解决方案将使用this
像这样:
var myModule = (function() { var init = function() { //Inicializar variáveis relacionadas ao DOM this.baner = $("#baner"); }; return { init: init, baner: undefined }; })(); $(document).ready(function() { myModule.init(); console.log(myModule.baner); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="#baner"></div>
After reading the article that @mhodges suggested, I figured out I could use a public function to return the private variable. 阅读@mhodges建议的文章后,我发现可以使用公共函数返回私有变量。 The result looks like this: 结果看起来像这样:
var myModule = (function(){
var _banerSegment;
var init = function(){
//Inicializar variáveis relacionadas ao DOM
_banerSegment = $('#baner');
};
var returnBaner = function(){
return _banerSegment;
}
return {
init: init,
baner: returnBaner
};
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.