I have a function defined inside a $('document').ready.
我在$('document')中定义了一个函数。
$('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.
但是当我在Chrome控制台调用init()时,我得到:ReferenceError: init没有定义。
Update: Thank you all for your help. I didwindow.init = init; and it works perfectly.
更新:谢谢大家的帮助。我didwindow。init =;和它工作得很好。
5 个解决方案
#1
3
Your init function is contained by the scope of the function you've passed to jQuery.ready. This is a good thing, it means you haven't created an unnecessary global.
您的初始化函数包含在您传递给jquery的函数的范围内。这是一件好事,它意味着您没有创建一个不必要的全局变量。
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.:
如果需要将函数导出到全局范围,可以通过显式地分配给窗口上的一个属性来实现,例如:
window.init = init;Since window is the global object on browsers, that would allow you to call it from Chrome's console without the window. prefix. But only do that if absolutely necessary, the global scope is already crowded enough.
由于窗口是浏览器上的全局对象,所以您可以在没有窗口的情况下从Chrome的控制台调用它。前缀。但只有在绝对必要的情况下,全球范围才会如此拥挤。
#2
1
Function declarations, like your function init() {}, are restricted to the scope they're defined in. If you want to use init elsewhere, do this:
函数声明,比如你的函数init(){},被限制在它们定义的范围内。如果您想在其他地方使用init,请执行以下操作:
var init;$('document').ready(function() { init = function() {};});#3
0
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:
我认为您希望将函数定义放在ready函数之外,即使函数引用文档,文档也不需要准备好定义函数。在我的代码中,直到函数实际执行时才执行函数内部的引用,函数定义就像定义一个文本常量。使用以下:
function visit(url) { $.pjax({ url: url, container: '#maincontainer', success: function(data) { init(); } });}function init() { ...}$(function () { init();});#4
0
Try something like this:
试试这样:
$('document').ready(function() { var objScope = this; function visit(url) { $.pjax({ url: url, container: '#maincontainer', success: function(data) { objScope.init(); } }); } function init() { ... })};#5
-1
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 a var there) which can be referenced anywhere.
如果您坚持这种方法,则使用init = funciton()语法。这将创建一个全局变量(因为您不会在其中放置一个var),可以在任何地方引用它。
That said, defining functions can be done at any time, there is absolutely no point in putting them in .ready().
也就是说,定义函数可以在任何时候完成,将它们放入.ready()中是毫无意义的。