如何将(document).ready添加到现有的jquery函数文件中

时间:2022-03-09 19:32:50

I have a jquery function file with function with AJAX functions in it. Now I need to add (document).ready function to the same file. My question is should I add this function outside of the existing function() block or keep it inside.

我有一个带有AJAX函数的函数的jquery函数文件。现在我需要将(document).ready函数添加到同一个文件中。我的问题是我应该在现有的function()块之外添加此函数还是将其保留在内部。

2 个解决方案

#1


1  

You can add it outside, if it's like so:

您可以在外面添加它,如果是这样的话:

function doMyAjax() {
    $.ajax({
        type: 'POST',
        stuff: more 
        ect...
    }).done(function(data) {
        $(element).html(data);
    });

    $("element").on('DOMNodeModified', function(event) {
        $(event.target).appendTo('body');
    });
}

$(function() {  //same as $(document).ready(function(){..});
    doMyAjax(); //function is executed after DOM is ready
});

or you can wrap all your code in it:

或者你可以将所有代码包装在其中:

$(function() {  //same as $(document).ready(function(){..});
    //all my code goes here and is executed after DOM is ready
});

Up 2 u !

快2你!

#2


0  

Add the $(document).ready() function outside of your included file, and from there call a function in your file to do whatever you need to do in you other code. i.e.

在你所包含的文件之外添加$(document).ready()函数,然后在你的文件中调用一个函数来做你需要做的其他代码。即

var myStuff = myStuff || {
   init: function() {
     ///run stuff needed in document.ready here
   }
}

$(document).ready(function(){
    myStuff.init();
});

The golden rule here is to call $(document).ready in only 1 place from each page.

这里的黄金法则是在每页的一个地方调用$(document).ready。

#1


1  

You can add it outside, if it's like so:

您可以在外面添加它,如果是这样的话:

function doMyAjax() {
    $.ajax({
        type: 'POST',
        stuff: more 
        ect...
    }).done(function(data) {
        $(element).html(data);
    });

    $("element").on('DOMNodeModified', function(event) {
        $(event.target).appendTo('body');
    });
}

$(function() {  //same as $(document).ready(function(){..});
    doMyAjax(); //function is executed after DOM is ready
});

or you can wrap all your code in it:

或者你可以将所有代码包装在其中:

$(function() {  //same as $(document).ready(function(){..});
    //all my code goes here and is executed after DOM is ready
});

Up 2 u !

快2你!

#2


0  

Add the $(document).ready() function outside of your included file, and from there call a function in your file to do whatever you need to do in you other code. i.e.

在你所包含的文件之外添加$(document).ready()函数,然后在你的文件中调用一个函数来做你需要做的其他代码。即

var myStuff = myStuff || {
   init: function() {
     ///run stuff needed in document.ready here
   }
}

$(document).ready(function(){
    myStuff.init();
});

The golden rule here is to call $(document).ready in only 1 place from each page.

这里的黄金法则是在每页的一个地方调用$(document).ready。