将jQuery代码移动到函数中?

Sam*_*tar 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");
              }
          }
      });

  });
Run Code Online (Sandbox Code Playgroud)

有没有办法可以采取此代码的操作并将其移动到一个函数.然后在我的$(document).ready(function(){中只对该函数进行一行调用

gdo*_*ica 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); 
 }()
 );
Run Code Online (Sandbox Code Playgroud)

  • 更短:`$(foo)`.OP的注意事项.当使用函数作为参数调用jQuery构造函数时,它是`$(document).ready(foo);`的缩写. (2认同)