如何在javascript中的函数之后添加$(document).ready(function(){})

时间:2014-03-12 04:47:32

标签: javascript jquery

我想要做的是我有一个如下代码:

$(document).ready(
  function(){
   var currentPage = window.location.pathname;
   $('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
  }  
)

现在我想添加此代码以添加并使用其他代码。我需要在此之后添加此代码:

function () {
    /* If there are forms, make all the submit buttons in the page appear
       disabled and prevent them to be submitted again to avoid accidental
       double clicking. See Issue 980. */
    jQuery(function() {
        /* Delegate the function to document so it's likely to be the last event
           in the queue because of event bubbling. */
        jQuery(document).delegate("form", "submit", function (e) {
            var form = jQuery(this);
            if (form.hasClass("form_disabled")) {
                e.preventDefault();
                return false;
            }
            else {
                form
                  .addClass("form_disabled")
                  .find(":submit")
                    .addClass("disabled");
            }
            // Reactivate the forms and their buttons after 3 secs as a fallback.
            setTimeout(function () {
                form
                  .removeClass("form_disabled")
                  .find(":submit")
                    .removeClass("disabled");
            }, 3000);
        });
    });
}

我怎样才能完成这项工作。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

您可以在脚本中的任何位置创建document.ready()。您的所有代码都不必处于就绪状态。

您可以为函数创建实例变量并在需要的地方调用它:

$(document).ready(
  var myFunc = function(){
   var currentPage = window.location.pathname;
   //other code
  }  
  ...
 //and invoke it where you need
  myFunc();
)

答案 1 :(得分:0)

首先,在代码部分中命名long函数,例如 launchFormControls()。然后在文档就绪事件之外定义函数。一个好的做法是这样做并保持准备好的活动体清洁。

例如:

function launchFormControls() {
   //function code
}

或者,在其他语法中:

var launchFormControls = function() {
   //function code
}

其次,从文档就绪事件中调用您的函数。您的功能将被定义,并且能够在加载文档后调用。此代码可以放在javascript部分或文件的顶部或底部。

例如:

$(document).ready(function(){
  var currentPage = window.location.pathname;
  $('#main-menu-list').find('a[href^="' + currentPage+'"]').closest('li').addClass('active');

  launchFormControls();
});
相关问题