将document.ready函数移至单独的javascript函数? [英] Move document.ready function to a separate javascript function?

查看:48
本文介绍了将document.ready函数移至单独的javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将jQuery document.ready函数中的以下代码移动到单独的javascript函数中,以便可以像调用其他任何javascript函数一样调用它,即:

Is it possible to move the following code within a jQuery document.ready function into a separate javascript function, so that it can be called just like any other javascript function, i.e.:

<script type="text/javascript"> 
$(document).ready(function()
{
   $('div#infoi img[title]').qtip({
      position: { 
         adjust: { x:-110, y:0 },
         corner: {
            target: 'bottomLeft',
            tooltip: 'topMiddle'
         }
      },
      style: {
        width: 250,
        padding: 5,
        background: '#E7F1FA',
        color: 'black',
        textAlign: 'center',
        border: {
          width: 3,
          color: '#65a9d7'
        },
        tip: 'topRight'
      }
   });
});
</script>

如果是,那么如何-否则,这回答了我的问题.

If yes, then how - if not, then that answers my question.

推荐答案

Pekka 的答案是正确的,但是您可能需要一些其他信息,例如怎么称呼它,例如,如果我们当前有这个:

Pekka's answer is correct, but you may want some other info, e.g. how to call it, so for example if we have this currently:

$(document).ready(function() {
  alert("DOM Ready!");
});

然后将其放在命名函数中,如下所示:

Then put it in a named function instead, like this:

function myFunc() {
  alert("DOM Ready!"); 
}

现在您可以在任何地方使用myFunc()调用它了...如果您仍然想在document.ready上调用它,语法也很短,就像这样:

Now you can call it using myFunc() anywhere...if you still want to call it on document.ready as well, the syntax is very short, like this:

$(myFunc);
//this is equivalent to:
$(document).ready(myFunc);

基本上,无论您在何处有匿名的function() { },都可以在其外部将其命名为 named 函数,并按上面的方法通过名称进行调用,对于.ready(myFunc)例子:)

Basically wherever you have an anonymous function() { }, you can name it a named function outside there and call it by name as I have above, the .ready(myFunc) could easily be $("#thing").click(myFunc) for example :)

这篇关于将document.ready函数移至单独的javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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