在其中创建功能是否正确
$(document).ready(function() {
像这样:
$(document).ready(function() {
function callMe() {
}
});
在.ready()函数内部不需要调用在dom之前就已经准备好了,并且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).
解决方法
是的,你可以做到这一点,只是一个范围的问题;如果你只需要从$(document).ready(function(){})中访问callMe(),那么把函数放在那里就可以了,并提供一些架构的好处,因为你不能访问那个上下文.如果您需要使用外部的callMe()函数准备好,则需要在该上下文之外定义callMe()函数.
function callMe() {
// Do Something
}
$(document).ready(function() {
callMe();
});
UPDATE
根据您的澄清,您有两个选择:
1)DECLARE变量外面的ready(),但是然后定义变量里面的ready()
var someVariable;
function callMe() {
someVariable++;
alert(someVariable);
}
$(document).ready(function() {
someVariable = 3;
callMe(); // Should display '4'
});
2)在ready中,使用window.yourVariable =’whatever’定义变量;