【问题标题】:jQuery init function with condition带有条件的jQuery初始化函数
【发布时间】:2017-12-12 11:12:32
【问题描述】:

我是脚本方面的新手,再次需要您的帮助来编写更好的代码。我正在使用 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();
});

【问题讨论】:

  • 不清楚您在这里要做什么 - abc 被硬编码为 0,因此您的条件永远不会受到影响。如果您想在 abc 值更改时执行一些逻辑,我建议您改用基于事件的模式。
  • 那些函数:在Init()里面,你应该把它们放在外面。
  • @RoryMcCrossan 朋友你能解释一下基于事件的模式吗? 'abc' 是我试图应用条件的一些虚拟变量。
  • @Zorkind 哪些函数可以放在外面?如果调用,条件函数将缓存DOM 一些元素。
  • 在你用逗号放置一些函数的条件之后,我认为那些应该在 Init() 之外?事实上,一切都在 Init() 中,除了 ConditionalFunctions 是

标签: jquery initialization init


【解决方案1】:

通过重写和定位你的代码,你可以这样写:

    $(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();
});

【讨论】:

  • 从来没有想过会这么简单 :) 谢谢朋友
猜你喜欢
  • 2011-09-04
  • 2011-01-02
  • 1970-01-01
  • 2011-01-13
  • 2012-05-22
  • 2021-02-07
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多