javascript - 如果函数处于错误情况下,我该如何停止执行?

标签 javascript

我正在构建一个为用户一周计划的网络应用程序,因此它需要:从、到、文本输入,如下面的屏幕截图所示:

enter image description here

因此,为了避免输入重复或输入重复,我为输入创建了两个数组,分别称为 fromAtoA,一切正常,除了我在使用 id 时遇到一些问题,那是因为当用户输入重复的值时会出现错误,并且 addItem 方法返回,如下面的屏幕截图所示

enter image description here

这是我的代码:

JavaScript:

var UIController = (function(interCtrl) {

  var DOMstrings = {
    inputDay: ".optionList",
    inputTimeF: ".inputTime",
    inputTimeT: ".inputTime2",
    inputText: ".inputText",
    goingToCkecked: ".checkboxx",
    inputBtn: ".add__btn",
    planContainer: ".container",
    errorCase: ".error-case",
    optionList: ".optionList",
    optionListId: "#optionList",
    errorDes: "error-description",
  };


  return {
    getInput: function() {
      return {
        inputDay: document.querySelector(DOMstrings.inputDay).value,
        inputTimeF: document.querySelector(DOMstrings.inputTimeF).value,
        inputTimeT: document.querySelector(DOMstrings.inputTimeT).value,
        inputText: document.querySelector(DOMstrings.inputText).value,
        goingToCkecked: document.querySelector(DOMstrings.goingToCkecked).checked,


      };
    },
    getDOMstrings: function() {
      return DOMstrings;
    },
    addPlanList: function(obj, day) {

      var html, element, newHtml;
      //1.CREATE HTML WITH A PLACEHOLDER TEXT
      if (day === "Monday" || day === "Tuesday" || day === "Wednesday" || day === "Thursday" || day === "Friday" || day === "Saturday" || day === "Sunday") {
        html = '<h1 class="day"> %day%</h1><div class="plan-%ID%" style="text-align:center"><i class="fas fa-calendar-check check"></i><span class=""><span class="from">FROM: </span><span>%timef%</span><span class="to"> TO: </span><span class="">%timet%</span> <span class="to-do">I\'m going to %text%</span><i class="fas fa-times-circle"></i><span class="line"></span></span></span></div>';


        //2.REPLACE THE PLACEHOLDER TEXT WITH SOME ACTUAL DATA

        if (obj.id === 0) {
          newHtml = html.replace('%day%', day);
          newHtml = newHtml.replace('%ID%', obj.id);
          newHtml = newHtml.replace('%timef%', obj.from);
          newHtml = newHtml.replace('%timet%', obj.to);
          if (obj.goingToCkecked === false) {
            newHtml = newHtml.replace('I\'m going to %text%', obj.text);
          } else {
            newHtml = newHtml.replace('%text%', obj.text);
          }
        } else {
          newHtml = html.replace('%day%', "");
          newHtml = newHtml.replace('%ID%', obj.id);
          newHtml = newHtml.replace('%timef%', obj.from);
          newHtml = newHtml.replace('%timet%', obj.to);

          //3.add or remove the "I'm going to" prefix
          if (obj.goingToCkecked === false) {
            newHtml = newHtml.replace('I\'m going to %text%', obj.text);
          } else {
            newHtml = newHtml.replace('%text%', obj.text);
          }
        }

        //4.insert the element in the DOM
        element = DOMstrings.planContainer;

        document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);

      }
    }
  };

})(internalController); //END OF THE UICONTROLLER MODULE




var internalController = (function(UICtrl) {

  var Plan = function(id, from, to, text, goingToCkecked) {
    this.id = id;
    this.from = from;
    this.to = to;
    this.text = text;
    this.goingToCkecked = goingToCkecked;
  };

  var data = {
    Monday: [],
    Tuesday: [],
    Wednesday: [],
    Thursday: [],
    Friday: [],
    Saturday: [],
    Sunday: []
  };

  var toA = [];
  var fromA = [];
  var errorCase = false;


  var Dom = UICtrl.getDOMstrings();

  function removeError(x, y) {
    document.querySelector(x).style.visibility = "hidden";
    document.querySelector(y).classList.remove("error-red");
  }

  function errorVisible(x, y) {
    document.querySelector(x).style.visibility = "visible";
    document.querySelector(y).classList.add("error-red");

  }

  return {

    addItem: function(day, from, to, text, goingToCkecked) {
      var newPlan, ID;

      //2.change the input color to white when the user pick a DAY (in the error case)
      document.querySelector(Dom.optionListId).addEventListener("change", function() {
        removeError(Dom.errorCase, Dom.optionList);
      });

      //1.THE ERROR MESSAGE  SHOWS UP IF THE DAY IS NOT PICKED RIGHT
      if (day === 'pick the day') {
        errorVisible(Dom.errorCase, Dom.optionList);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should pick a day";
      }


      //4.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "FROM" INPUT
      document.querySelector(Dom.inputTimeF).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputTimeF);
      });

      //3.IF THE FROM INPUT IS EMPTY THE ERROR SHOWS UP  AND BLOCK THE APP AT THAT POINT
      if (from === "") {
        errorVisible(Dom.errorCase, Dom.inputTimeF);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" from \" input";
        errorCase = true;
        return;
      }

      //refuse dupicated from values
      if (fromA.includes(from) === false && to != "" && text != "" && errorCase === false && day != "pick the day") {

        fromA.push(from);
        console.log("from array:")
        console.log(fromA);
        errorCase=false;

      } else if (fromA.includes(from) === true) {
        errorVisible(Dom.errorCase, Dom.inputTimeF);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" from \" time is already chosen";
        errorCase = true;
        return;
      }


      //6.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "TO" INPUT
      document.querySelector(Dom.inputTimeT).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputTimeT);
      });

      //5.IF THE TO INPUT IS EMPTY THE ERROR SHOWS UP

      if (to === "") {
        errorVisible(Dom.errorCase, Dom.inputTimeT);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" to \" input";
        return;
      }

      if (toA.includes(to) === false && from != "" && text != "" && errorCase === false && day !="pick the day") {

        toA.push(to);
        console.log("to array:");
        console.log(toA)
        errorCase=false;

      } else if (toA.includes(to) === true) {
        errorVisible(Dom.errorCase, Dom.inputTimeT);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "the \" to \" time is already chosen";
        return;
      }


      //7.REMOVE THE ERROR MESSAGE AS WELL AS THE RED COLOR FROM THE "TEXT" INPUT

      document.querySelector(Dom.inputText).addEventListener("keypress", function() {
        removeError(Dom.errorCase, Dom.inputText);
      });


      if (text === "") {
        errorVisible(Dom.errorCase, Dom.inputText);
        document.getElementsByClassName(Dom.errorDes)[0].innerHTML = "you should fill the \" text \" input";
        return;
      }




      //CREATE NEW ID
      if (data[day].length > 0) {
        ID = data[day][data[day].length - 1].id + 1;
      } else {
        ID = 0;
      }



      //CREATE NEW PLAN BASED ON THE PICKED DAY

      if (day === "Monday" || day === "Tuesday" || day === "Wednesday" || day === "Thursday" || day === "Friday" || day === "Saturday" || day === "Sunday") {
        newPlan = new Plan(ID, from, to, text, goingToCkecked);
      }



      //PUSH IT INTO OUR DATA STRUCTURE
      data[day].push(newPlan);

      //RETURN THE NEW ELEMENT
      return newPlan;

    }, //END OF THE ADD ITEM METHOD

    clearFields: function(fromInput, toInput, txtInput) {

      // get the from input back to the default value
      document.querySelector(fromInput).value = "";

      //get the "TO" input back to the default value
      document.querySelector(toInput).value = "";

      //get the "text" input back to it's default value
      document.querySelector(txtInput).value = "";

    },



  }; //end of the return object of the internal controller module


})(UIController);





var controller = (function(interCtrl, UICtrl) {
  var input,  DOM,newPlan;

  DOM = UICtrl.getDOMstrings();

  function setupEventListeners() {

    document.querySelector(DOM.inputBtn).addEventListener("click", ctrlAddPlans);

    document.addEventListener("keypress", function(e) {
      if (e.keyCode === 13) {
        document.activeElement.blur();
        ctrlAddPlans();
      }
    });

  }

  var ctrlAddPlans = function() {

    //3.get the filed input data
    input = UICtrl.getInput();

    //5.add the plan to the internalController

    newPlan = interCtrl.addItem(input.inputDay, input.inputTimeF, input.inputTimeT, input.inputText, input.goingToCkecked);

    //6.add the plan to the UI
    UICtrl.addPlanList(newPlan, input.inputDay);

    //7.clear the fields;

    interCtrl.clearFields(UICtrl.getDOMstrings().inputTimeF, UICtrl.getDOMstrings().inputTimeT, UICtrl.getDOMstrings().inputText);

  };

  return {
    init: function() {
      console.log('the app has started');
      setupEventListeners();
    },

  };
})(internalController, UIController);


controller.init();

我知道问题来自 obj 因为它是未定义的所以我想问的是如果函数处于错误情况下我如何停止执行我使用了 return 关键字关于 errorCase 的 if 语句,但它不起作用,如果您需要,我可以包含它

最佳答案

在第 6 条评论中,您可以将该函数调用包装到 if 语句中:

if(newPlan){
  UICtrl.addPlanList(newPlan, input.inputDay);
}

关于javascript - 如果函数处于错误情况下,我该如何停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314687/

相关文章:

javascript - 使用 javascript google calendar api v3 获取某一天的事件

javascript - Ember mixins - 这是实现 'dynamic' 布局的好方法吗

javascript - 如何在我的网站上启用 Google map 中的旅游景点图标?

javascript - ReactJS Koans 杂货 list 第 1 部分

javascript - 使用 Collide() 函数时,P5 中的对象不会发生碰撞

javascript - Zurb 基础 4 部分和 jQuery 效果

javascript - CSS 与 JavaScript - 无法读取属性 'undefined' 错误

javascript - 用户缩放时不同类型图像的不同行为

返回递归函数的 Javascript 闭包

javascript - 为 Rails 生成的 XML API 构建 JavaScript 包装器?