if / else调用该函数,其余逻辑是相同的

时间:2013-09-19 15:04:21

标签: javascript jquery html jquery-ui javascript-events

我在js函数中有一个js代码... 这包含if else条件...其中包含相同的功能只有参数更改......

所以唯一不同的是你传递给函数的参数字符串...... 使用if / else来调用函数,其余的逻辑是相同的......

是否可以调用该函数,其余的逻辑是相同的.....

return $(this).each(function () {
                if (coffeeId == "showCoffeeId") {
                    var todayDate = NoteWorklist.getDateTime("appleTime");
                    value.Year = todayDate.getFullYear();
                    value.Month = todayDate.getMonth() + 1;
                    value.Day = todayDate.getDate();
                    value.today = todayDate;
                    value.inputDate = todayDate;
                } else {
                    var todayDate = NoteWorklist.getDateTime("orangeTime");
                    value.Year = todayDate.getFullYear();
                    value.Month = todayDate.getMonth() + 1;
                    value.Day = todayDate.getDate();
                    value.today = todayDate;
                    value.inputDate = todayDate;
                }
            });

4 个答案:

答案 0 :(得分:4)

只需使用三元运算符:

return $(this).each(function () {
       var todayDate = NoteWorklist.getDateTime(coffeeID == "showCoffeeId" ? "appleTime" : "orangeTime");
       value.Year = todayDate.getFullYear();
       value.Month = todayDate.getMonth() + 1;
       value.Day = todayDate.getDate();
       value.today = todayDate;
       value.inputDate = todayDate;
});

答案 1 :(得分:1)

当然可以:

return $(this).each(function () {

    var todayDate = NoteWorklist.getDateTime(coffeeId == "showCoffeeId" ? "appleTime" : "orangeTime");
    value.Year = todayDate.getFullYear();
    value.Month = todayDate.getMonth() + 1;
    value.Day = todayDate.getDate();
    value.today = todayDate;
    value.inputDate = todayDate;

});

答案 2 :(得分:1)

    if (coffeeId == "showCoffeeId") {
       var todayDate = NoteWorklist.getDateTime("appleTime");
    } else {
      var todayDate = NoteWorklist.getDateTime("orangeTime");
    }

    value.Year = todayDate.getFullYear();
    value.Month = todayDate.getMonth() + 1;
    value.Day = todayDate.getDate();
    value.today = todayDate;
    value.inputDate = todayDate;

答案 3 :(得分:0)

像这样?

return $(this).each(function () {
      var word =""
      if (coffeeId == "showCoffeeId") {
           word = "appleTime";
      } else {
           word = "orangeTime";
      }
     var todayDate = NoteWorklist.getDateTime(word);
     value.Year = todayDate.getFullYear();
     value.Month = todayDate.getMonth() + 1;
     value.Day = todayDate.getDate();
     value.today = todayDate;
     value.inputDate = todayDate;
});