我有一个名为 text.js 的文件,它有
var Text = function(canvas){
var textField = $('#textField'),
addTextButton = $('#addText');
var init = function(){
addTextButton.click(function(){
alert('won"t work?')
});
},
resetTextField = function(){
// it work if I put the selector here like var textField = $('#textField'),
textField.val(''); // won't work
};
return{
init:init
}
}();
它包含在我的index.html 中。在那里我像
那样初始化$(function(){
Text.init();
}());
问题是事件无法被触发。我想我搞砸了一些事情。
最佳答案
Text
中的代码立即运行,并返回 init
的对象在上面。如果您在它查找的元素存在之前运行该代码,例如:
<!doctype html>
<html>
<head>
<!-- ... --->
<script src="text.js"></script><!-- Problem here -->
<script>
$(function(){
Text.init();
}());
</script>
</head>
<body>
<!-- ... --->
<input id="textField"><input id="addText" type="button" value="Add">
<!-- ... -->
</body>
</html>
...您最终会在 textField
中得到空的 jQuery 对象和addTextButton
.
另外,您还运行您尝试传递的函数 ready
立即(然后将 undefined
传递给 ready
),问题就在这里:
$(function(){
Text.init();
}());
// ^^---------- problem
你不想要那些()
。您想将函数传递到 ready
:
$(function(){
Text.init();
}); // <== Note no ()
如果您想要 init
方法,最好将所有初始化放在其中,而不是放在两个地方:
var Text = function(canvas){
var textField, addTextButton;
var init = function(){
textField = $('#textField');
addTextButton = $('#addText');
addTextButton.click(function(){
alert('won"t work?')
});
},
resetTextField = function(){
// it work if I put the selector here like var textField = $('#textField'),
textField.val(''); // won't work
};
return{
init:init
}
}();
但请注意,如果您遵循 usual best practice将脚本放在文档的末尾,就在结束之前 </body>
标签,上面定义的元素将存在并且可用,这将使得使用 ready
(和 init
)不必要。所以如果你控制script
的位置标签走,这是一个选项。
例如:
<!doctype html>
<html>
<head>
<!-- ... --->
</head>
<body>
<!-- ... -->
<input id="textField"><input id="addText" type="button" value="Add">
<!-- ... -->
<script src="text.js"></script>
<script>
$(function(){
Text.init();
});
</script>
</body>
</html>
关于javascript - 揭示模块模式和 jquery 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41459938/