在内部创建函数是否正确
$(document).ready(function() {
像这样:
$(document).ready(function() {
function callMe() {
}
});
在 DOM 准备好并且触发 ready()
内部的事件之前,不必调用 .ready()
内部的函数。
只是为了澄清一点 - 这是说明问题的代码:
$(function() {
var ind = 0;
// some event is executed and changes the value of the ind
// another event which affects the ind variable
// and another one - after this event we call our function
// there's another event - and we call our function again
我需要调用的函数需要 ind
变量的更新值 - 我想我可以将其作为参数传递,但是有更好的方法吗?
另外 - 另一件重要的事情是,所涉及的 function()
还可以更改 ind
变量的值 - 例如递增它 (ind++
)。
最佳答案
是的,你可以这么做,只是 scope 的问题.
如果您只需要从 $(document).ready(function() { })
中访问 callMe()
,那么可以将函数放在那里,并提供一些架构优势,因为您无法访问该上下文之外的函数。
如果您需要在文档就绪之外使用 callMe()
函数,则需要在该上下文之外定义 callMe()
函数。
function callMe() {
// Do Something
}
$(document).ready(function() {
callMe();
});
<小时/>
更新
根据您的说明,您有两种选择:
1) 在 ready()
外部声明变量,然后在 ready()
内部定义变量:
var someVariable;
function callMe() {
someVariable++;
alert(someVariable);
}
$(document).ready(function() {
someVariable = 3;
callMe(); // Should display '4'
});
2) 在 ready()
中,使用 window.yourVariable = 'whatever';
定义变量
关于jQuery - $(document).ready 函数中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780890/