在 $('document').ready 中调用函数
我在 $('document').ready
中定义了一个函数。
$('document').ready(function() {
function visit(url) {
$.ajax({
url: url,
container: '#maincontainer',
success: function(data) {
init();
}
});
}
function init() {
...
}
)};
但是当我在 Chrome 控制台中调用 init()
时,我得到:ReferenceError: init is not Defined
。
更新:感谢大家的帮助。我做了window.init = init;
并且它工作得很好。
I have a function defined inside a $('document').ready
.
$('document').ready(function() {
function visit(url) {
$.ajax({
url: url,
container: '#maincontainer',
success: function(data) {
init();
}
});
}
function init() {
...
}
)};
But when I call init()
in Chrome Console I get : ReferenceError: init is not defined
.
Update: Thank you all for your help. I didwindow.init = init;
and it works perfectly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的
init
函数包含在您传递给jQuery.ready
的函数范围内。这是一件好事,它意味着您没有创建不必要的全局。如果需要将函数导出到全局范围,可以通过显式分配给
window
上的属性来实现,例如:由于
window
是 浏览器上的全局对象,这将允许您从 Chrome 的控制台调用它,而无需窗口。
前缀。但只有在绝对必要时才这样做,全球范围已经足够拥挤了。Your
init
function is contained by the scope of the function you've passed tojQuery.ready
. This is a good thing, it means you haven't created an unnecessary global.If you need to export the function to the global scope, you can do so by explicitly assigning to a property on
window
, e.g.:Since
window
is the global object on browsers, that would allow you to call it from Chrome's console without thewindow.
prefix. But only do that if absolutely necessary, the global scope is already crowded enough.函数声明(例如
function init() {}
)仅限于它们定义的范围。如果您想在其他地方使用 init,请执行以下操作:Function declarations, like your
function init() {}
, are restricted to the scope they're defined in. If you want to use init elsewhere, do this:我认为您想将函数定义放在就绪函数之外,即使函数引用了文档,文档也没有必要准备好定义函数。请记住,函数内部的引用只有在函数实际执行时才会执行,函数定义就像定义文本常量一样。请改用以下内容:
I think you want to put your function definition outside the ready function, it is not necessary for the document to be ready to define a function even if the function references the document. Keep in mine the references inside a function are not performed until the function is actually executed, a function definition is just like defining a text constant. Use the following instead:
尝试这样的事情:
Try something like this:
函数仅在您定义它们的范围内定义。
如果您坚持使用此方法,请改用
init = funciton()
语法。这将创建一个可以在任何地方引用的全局变量(因为您不会在那里放置var
)。也就是说,定义函数可以随时完成,将它们放在
.ready()
中绝对没有意义。Functions are only defined the scope you define them in.
If you insist on this method, use
init = funciton()
syntax instead. This will create a global variable (since you're not going to put avar
there) which can be referenced anywhere.That said, defining functions can be done at any time, there is absolutely no point in putting them in
.ready()
.