jQuery - $(document).ready 函数中的函数

标签 jquery document document-ready

在内部创建函数是否正确

$(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/

相关文章:

javascript - AJAX/jQuery 生成的输入无法被其他 jQuery 脚本识别

jquery - 使用 jquery 隐藏/显示表格 CSS 的行

javascript - 使用 document.ready 与 window.load 加载延迟内容

javascript - 使用 jQuery 结果渲染多个 div

javascript - javascript 中的正则表达式匹配可以匹配等于运算符后面的任何单词吗?

cocoa - 在基于文档的 Cocoa 应用程序中实现导出功能的公认方法是什么?

jquery - $(document).ready() 在 jQuery-AJAX 调用中立即触发

javascript - 在 Javascript 中触发 DOMContentLoaded 时,如何找出正在执行的内容?

android - 在 Android 中使用什么文档格式来呈现内容?

document - 如何更新嵌入式文件?