简体   繁体   English

有没有一种方法可以确定某个功能是否正在准备就绪的文档中运行?

[英]Is there a way to determine if a function is running in document ready or not?

Is there a way to determine if a function is running in document ready? 有没有办法确定某个功能是否正在准备就绪的文档中运行?

I mean something like this: 我的意思是这样的:

function myfunction() {
    var isinside = //... what to write here?
    if (isinside) {
    }
}

(It is also possible my (very beginner) concept is not optimal, so I write what I am trying to achieve: (也有可能我的(初学者)概念不是最佳的,所以我写了我想达到的目标:

I would like to create a reusable object, what can instantiated in multiple instances within a page (hopefully with one line of JavaScript per instance). 我想创建一个可重用的对象,该对象可以在页面中的多个实例中实例化(希望每个实例一行JavaScript)。 However there are things what this object must do in document ready, like attaching event handlers.) 但是,在准备好文档后,此对象还必须做一些事情,例如附加事件处理程序。)

I am not sure why you have a problem here? 我不确定您为什么在这里遇到问题? The calling code is normally responsible for being in a DOM ready handler, or not, not the functions. 调用代码通常负责是否在DOM就绪处理程序中,而不是在函数中。

You can just put a DOM ready redundantly inside any function, if needed, but this sounds like an odd situation so you need to show the rest of the code. 可以根据需要将DOM 冗余地放入任何函数中,但这听起来很奇怪,因此您需要显示其余代码。

eg any function can have a DOM ready handler: 例如,任何函数都可以具有DOM ready处理程序:

function myfunction() {
    $(document).ready(function(){
         // I am inside DOM ready!
         // Connect my DOM element events here
    });
    // Do my other non-element stuff here
}

or, shorter: 或更短:

function myfunction() {
    $(function(){
         // I am inside DOM ready!
         // Connect my DOM element events here
    });
    // Do my other non-element stuff here
}

The key here is that DOM ready handlers can be called after DOM ready and they fire immediately. 这里的关键是DOM就绪处理程序可以在DOM就绪后调用,并且它们会立即触发。

The downside to this is that you cannot rely on a return value as DOM ready is potentially async. 缺点是您不能依赖返回值,因为DOM ready可能是异步的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM