2012-01-17 57 views
0

我有我申请当文档准备好下面的代码:将jQuery代码移入一个函数?

$(document).ready(function() { 

     $('#updateDialog').dialog({ 
      autoOpen: false, 
      width: 400, 
      resizable: false, 
      modal: true, 
      buttons: { 
       "Update": function() { 
        $("#update-message").html(''); //make sure there is nothing on the message before we continue       
        $("#updateReferenceForm").submit(); 
       }, 
       "Cancel": function() { 
        $(this).dialog("close"); 
       } 
      } 
     }); 

    }); 

有,我可以利用这个代码的行为,并将其移动到一个函数的方式。然后,只需有我的$里面一行调用该函数(文件)。就绪(函数(){

+0

为什么不自己尝试一下呢? – gdoron 2012-01-17 10:44:01

回答

5

是的,它是非常简单的:

function foo() 
{ 
     $('#updateDialog').dialog({ 
     autoOpen: false, 
     width: 400, 
     resizable: false, 
     modal: true, 
     buttons: { 
      "Update": function() { 
       $("#update-message").html(''); //make sure there is nothing on the message before we continue       
       $("#updateReferenceForm").submit(); 
      }, 
      "Cancel": function() { 
       $(this).dialog("close"); 
      } 
     } 
    });  
} 

// First way: 
$(function(){ 
    foo(); 
}); 

// Second way: 
$(document).ready(function() { 
    foo() 
}); 

// Mathias Bynens version to save conflicts with global vars. 
(function() { 
    var foo = function() { /* do something */}; 
    $(foo); 
}() 
); 
+2

甚至更​​简短:'$(foo)'。对于OP来说,当调用jQuery构造函数作为参数时,它的'$(document).ready(foo); '。 – 2012-01-17 10:41:55

+0

这将创建一个全局变量('foo'),这是应该避免的。 – 2012-01-17 10:43:00

+0

@RobW,没有完成编辑答案,我稍后添加它...... =) – gdoron 2012-01-17 10:44:47

1

当然,使用这个样本:

$(document).ready(function() { 
    MyBlah("hello"); 
}); 

function MyBlah(blah) { 
    alert(blah); 
} 
相关问题