访问函数的$(document)文件。就绪(函数()
问题描述:
根据这个帖子Click here to see the referred post
我试图让访问哪些是在后指令之后另一个.js文件中定义的函数。不过,我仍然有一个问题,请参见下面我的代码:
sildemenu.js
$(document).ready(function() {
var window.slideMenu=function(){
//do something here
}();
});
control.js
$(document).ready(function() {
$('#foo').on('click', function() {
window.slideMenu();
});
});
我得到了错误“Object [object Window] has no method'sildeMenu'”。 我在编程方面很新颖。请给我一个怜悯。
答
您尝试定义一个复杂变量(这是不可能的),而不是为全局对象赋值(window
)。
var window.slideMenu=function(){
//^^^ Get rid of this
//do something here
}();
//^^ and remove this
,摆脱了var
固定代码:
window.slideMenu=function(){
//do something here
};
+0
我确实应用了你的固定代码,但是,我仍然得到了同样的错误。看起来'slidemenu.js'很好,但是错误来自'control.js'。 – 2013-02-20 10:29:42
答
没有必要window对象的只写:
sildemenu.js
$(document).ready(function() {
slideMenu=function(){
//Do your stuff here!
};
});
个
control.js
$(document).ready(function() {
$('#foo').on('click', function() {
slideMenu();
});
});
的'执行,因为'VAR window.slideMenu'是一个语法错误(和gdoron提到这个问题)sildemenu.js'失败。放下'var'。我建议阅读http://www.netmagazine.com/tutorials/javascript-debugging-beginners。 – 2013-02-20 10:11:06
如果你正确地阅读了链接的问题/答案,你会发现在函数定义之后没有'()','window ....'之前没有'var'。 – 2013-02-20 10:15:18