代码之家  ›  专栏  ›  技术社区  ›  user1231648

带条件的jQuery init函数

  •  0
  • user1231648  · 技术社区  · 8 年前

    我不熟悉脚本方面,再次需要您的帮助来编写更好的代码。我使用的是init函数,它是所有函数的集合,但现在如果某些条件成立,我似乎不想执行多少函数。

    示例脚本

     $(document).ready(function() {
    
    var app = {
    init: function(){
    
      // Variable to check condition
      var abc = 0;
    
      // Default functions
      this.Function1();
      this.Function2();
      this.Function3(); // abc variable will change to 1 if condition is true
    
      // Conditional functions
      if ( abc === 1 ) {
         this.ConditionFunction1();
         this.ConditionFunction2();
      },
    
      Function1: function(){ // some Code },
      Function2: function(){ // some Code },
      Function3: function(){
                    if(true) { abc == 1; } 
      },
      ConditionFunction1: function(){ // some Code },
      ConditionFunction2: function(){ // some Code }
    
    }
    app.init();
    });
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   sven.kwiotek    8 年前

    通过重写和对代码进行定向,您可以这样编写:

        $(document).ready(function () {
    
        var app = {
            init: function () {
    
                // Variable to check condition
                var abc = 0;
                var Function1 = function () { // some Code
                    console.log("Function1")
                }
    
                Function2 = function () { // some Code
                    console.log("Function2")
    
                }
    
                Function3 = function () {
                    if (true) {
                        console.log("Function3")
                        abc == 1;
                    }
                }
    
                ConditionFunction1 = function () { // some Code
                    console.log("ConditionFunction1")
                }
    
                ConditionFunction2 = function () { // some Code
                    console.log("ConditionFunction2")
                }
                // Default functions
                Function1();
                Function2();
                Function3(); // abc variable will change to 1 if condition is true
    
                // Conditional functions
                if (abc === 1) {
                    ConditionFunction1();
                    ConditionFunction2();
                }
            }
        }
        app.init();
    });