我正在努力提高我的js foo并开始更多地使用模块模式,但我正在努力。
我有一个带有jquery-ui元素的主页面,弹出一个对话框,加载一个ajax请求的页面进行数据输入。以下代码包含在弹出式ajax页面中。
加载弹出窗口后,Chrome控制台即可正常查看并执行ProtoSCRD.testing()
。如果我尝试在页面上的jQuery.ready块中运行它,我会得到:
未捕获的ReferenceError:未定义ProtoSCRD
然而,我可以在准备好的块中执行toggleTypeVisable()
,生活是美好的。任何人都能解释一下吗?
$(document).ready(function() {
setHoodStyleState();
$('#hood-style').change(function(){
hstyle = $('#hood-style').val();
if ( hstyle.indexOf('Custom') != -1) {
alert('Custom hood style requires an upload drawing for clarity.');
}
setHoodStyleState();
});
setCapsState();
$('#caps').change(function(){
setCapsState();
});
setCustomReturnVisibility();
$('#return').change(function(){ setCustomReturnVisibility(); });
toggleTypeVisable();
$('#rd_type').change(function(){
toggleTypeVisable();
});
ProtoSCRD.testing();
});
function toggleTypeVisable(){
if ( $('#rd_type').val() == 'Bracket' ) {
$('.endcap-ctl').hide();
$('.bracket-ctl').show();
}
if ( $('#rd_type').val() == 'Endcap' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').show();
}
if ( $('#rd_type').val() == 'Select One' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').hide();
}
}
ProtoSCRD = (function($, w, undefined) {
testing = function(){
alert('testing');
return '';
}
getDom = function(){
return $('#prd-order-lines-cnt');
}
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
像这样调用弹出对话框 - 实际上是在父页面上的diff文件中另一个准备就绪:
// enable prototype button
$( "#proto-btn" ).click(function(e){
e.preventDefault();
showPrototype();
});
答案 0 :(得分:3)
我不知道它是否会解决你的问题,但你肯定错过了你应该拥有的几个var
陈述:
var ProtoSCRD = (function($, w, undefined) {
var testing = function(){
alert('testing');
return '';
};
var getDom = function(){
return $('#prd-order-lines-cnt');
};
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
恕我直言,最佳做法是对您声明的每个变量使用var
。 (函数声明隐含地这样做。)
但我真的不知道这是否有助于解决任何问题。但它应该将所有内容存储在适当的范围内。
这是一个可能的问题:如果文档已经准备好(比如说这是在正文的末尾加载),那么jQuery可能会同步运行它。您是否尝试将ProtoSCRD
块的定义移到document.ready
块之上?