如何在document.ready块外部解雇jQuery?

时间:2012-02-03 19:19:22

标签: javascript jquery

启动jQuery的常用方法是将其放入

$(document).ready(function() {
    // put all jQuery stuff here
});

但是如果我有一个复杂的网站在<head> 中使用基本jQuery并且某些依赖于页面类型的自定义函数(例如,如果我有登录页面,请点击登录ajax)内容)。

那么,我如何将代码附加到$(document).ready() 以后再将其解雇?我应该使用哪种JS语法?

感谢您的帮助!


我的页面结构与此类似:

  1. 使用PHP的include()
  2. 显示静态标头
  3. <body></body>
  4. 中添加内容
  5. 显示模板页脚

  6. <?php
    
    include_once('system/classes/class.display.php');
    
    $d = new IFDisplay();
    
    $d->display_header(array('subtitle' => 'Log In')); <-- Here it displays static
                                                           head tags. There is
                                                           document.ready in there.
                                                           I can't change it.
    
    ?>
    
    <script type="text/javascript">
    AND WHAT DO I NEED TO PUT HERE
    </script>
    
    <div>...</div>
    
    <?php
    
    $d->display_footer();
    
    ?>
    

2 个答案:

答案 0 :(得分:4)

如果您不担心竞争条件,您应该能够使用它:

$(function(){
    //put your code here
});

随心所欲。

答案 1 :(得分:2)

如果你有一个代码块,你希望能够在$(document).ready()函数中运行BOTH,并且稍后在ajax调用完成时,那么你可以定义一个函数并将其称为两个像这样:

// define this in the global scope or some other publicly available scope (not inside a document.ready() call).
function myOperation() {
   // put your code here
}

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

然后,稍后(比如在其他代码中的ajax调用中),你可以用这个调用相同的函数:

myOperation()