jQuery-$(document).ready函数内部的函数 [英] jquery - function inside $(document).ready function

查看:143
本文介绍了jQuery-$(document).ready函数内部的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在内部创建函数是否正确

Is it correct to create functions inside of

$(document).ready(function() {

像这样:

$(document).ready(function() {
     function callMe() {

     }
 });

.ready()内部的函数不必在dom准备就绪且触发ready()内部的事件之前调用.

The function inside of the .ready() does not have to call before dom is ready and event inside of the ready() is triggered.

只需澄清一点-这是说明问题的代码:

Just to clarify a little bit - here's the code which would illustrate the problem:

$(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变量的值-我猜我可以将其作为参数传递,但是有更好的方法吗?

The function which I need to call needs the updated value of the ind variable - which I guess I could pass as a parameter, but is there a better way of doing it?

另外-另一个重要的事情是,所讨论的function()也可以更改ind变量的值-例如,将其递增(ind++).

Also - another important thing is that the function() in question can also change the value of the ind variable - for instance incrementing it (ind++).

推荐答案

是的,您可以做到,这只是范围的问题;如果您只需要从$(document).ready(function() { })内部访问callMe(),则可以将函数放在此处,这会带来一些体系结构上的好处,因为您无法在该上下文之外访问该函数.但是,如果您需要在准备就绪的文档之外使用callMe()函数,则需要在该上下文之外定义callMe()函数.

Yes, you can do that, it's just a matter of scope; if you only need to access callMe() from within $(document).ready(function() { }), then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context. If you need to use the callMe() function outside of document ready though, you need to define the callMe() function outside of that context.

function callMe() {
  // Do Something
}

$(document).ready(function() {
  callMe();
});

更新

根据您的澄清,您有两种选择:

Based on your clarification, you have two options:

1)在ready()之外的DECLARE变量,然后在ready()内定义变量

1) DECLARE variable outside of ready(), but then define variable inside of ready()

var someVariable;
function callMe() {
  someVariable++;
  alert(someVariable);
}

$(document).ready(function() {
  someVariable = 3;
  callMe(); // Should display '4'
});

2)在就绪状态下,使用window.yourVariable = 'whatever';

2) Within ready, define variables using window.yourVariable = 'whatever';

这篇关于jQuery-$(document).ready函数内部的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆