4

I have a js file containing my all jquery code all, I followed 2 practices but I don't know which one is better:

First:

jQuery(document).ready(function(){
    var $ = jQuery;

    //some code here

    //another code not related to the first one

    //also another independent code

    //... and so on
});

Second:

jQuery(document).ready(function(){
    //call the functions here
    my_func_1();
    my_func_2();
    my_func_3();
    my_func_4();
});

//list of functions
function my_func_1() {
   //function code
}

function my_func_2() {
   //function code
}

function my_func_3() {
   //function code
}

function my_func_4() {
   //function code
}

the second method seems better and more organized, but sometime let's say that my_func_2() didn't find what it's looking for on the page for example $('#my-id'), the functions that follow my_func_2() never run.

I also tried another method, define all my jquery functions in one js file, and then adding the function using script tags in the html where they should be:

<script>my_func_2();</script>

so what is the best way to group jquery code ?

and should we use :

jQuery(document).ready(function(){
});

for each bunch of code ?

and thanks in advance.

4

4 回答 4

2

如果您在 func_2() 中的代码可能会导致错误,那么您确实应该将函数的内容包装在 try / catch 块中,以确保下一个函数运行时没有问题。

此外,以下也是多个启动功能的选项,同时保持它们的错误范围分开:

$(document).ready(function(e) { ... My function code 1 .... });
$(document).ready(function(e) { ... My function code 2 .... });
$(document).ready(function(e) { ... My function code 3 .... });
$(document).ready(function(e) { ... My function code 4 .... });
于 2012-04-27T09:43:57.267 回答
1
var myFunc1 = function() {};
var myFunc2 = function() {};
var myFunc3 = function() {};
var myFunc4 = function() {};

首先声明你的函数。看看这个缩短器jQuery.ready

jQuery(function($) {
    // in here $ === jQuery.
    myFunc1();
    myFunc2();
    myFunc3();
    myFunc4();
});
于 2012-04-27T10:01:09.630 回答
0

一般来说,保持函数简短和简洁是一种很好的做法。此外,请考虑将代码拆分为小单元有助于您在其他地方重用它。

此外,您应该牢记测试代码的方面。测试小的独立代码单元比测试大块代码要容易得多。

于 2012-04-27T09:36:19.450 回答
0

将函数定义放在里面的意义$.ready()在于,这些函数被封闭在该上下文中,并且无法从外部访问。这可能是一个优势(访问封闭的变量或防止函数滥用),但会使调试变得更加困难。

根据我的经验,开始在外部声明你的函数(这样你就可以轻松地测试你的代码),而不是将这些函数移动到$.ready().

于 2012-04-27T10:18:59.477 回答