将jQuery代码移动到函数中?

时间:2012-01-17 10:40:02

标签: 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");
              }
          }
      });

  });

有没有办法让我可以采取此代码的操作并将其移动到一个函数。然后在$(document).ready(function(){

中)对这个函数进行一行调用

2 个答案:

答案 0 :(得分: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); 
 }()
 );

答案 1 :(得分:1)

当然,请使用此示例:

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

function MyBlah(blah) {
    alert(blah);
}