jquery - $(document).ready函数内的函数

use*_*341 28 jquery document document-ready

在其中创建函数是否正确

$(document).ready(function() {
Run Code Online (Sandbox Code Playgroud)

像这样:

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

     }
 });
Run Code Online (Sandbox Code Playgroud)

.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
Run Code Online (Sandbox Code Playgroud)

我需要调用的函数需要ind变量的更新值- 我想我可以将其作为参数传递,但是有更好的方法吗?

另外 - 另一个重要的事情是,function()问题还可以改变ind变量的值- 例如递增它(ind++).

Mik*_*rds 45

是的,你可以做到这一点,这只是一个范围问题; 如果您只需callMe()要从内部访问$(document).ready(function() { }),那么将函数放在那里是很好的,并提供一些架构优势,因为您无法访问该上下文之外的函数.如果您需要在文档就绪之外使用callMe()函数,则需要在该上下文之外定义callMe()函数.

function callMe() {
  // Do Something
}

$(document).ready(function() {
  callMe();
});
Run Code Online (Sandbox Code Playgroud)

UPDATE

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

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

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

$(document).ready(function() {
  someVariable = 3;
  callMe(); // Should display '4'
});
Run Code Online (Sandbox Code Playgroud)

2)在准备好之内,使用定义变量 window.yourVariable = 'whatever';

  • 是的,如果可能的话,我会说尽量避免全局变量.原因是因为它获得了MESSY.如果您有多个函数读/写,那么事情会变得很快.话虽如此,有一些方法可以更好地组织全局变量,例如对象文字,它可以帮助分组功能和属性. (2认同)

小智 5

这也将起作用。

$(document).ready(function() {
      callMe = function() {
            alert('hello');
      }
});

callMe();
Run Code Online (Sandbox Code Playgroud)

如果你使用

 var callMe = function () { ... }
Run Code Online (Sandbox Code Playgroud)

它可能不起作用,您可能会收到错误“函数未定义”