如果输入字段为空并且用户按空白输入命中输入,我只想打印一次消息。我哪里错了

时间:2018-04-30 12:22:45

标签: javascript if-statement

form.addEventListener('submit', (e) => { //create new invitee name
let text = input.value; //collect text value from input field
let counter = 0;
if (text != "") {
    createLI(text); //executes function to add new invitee. 
} else {. /*if text field is blank error message to be printed only once regardless on multiple entries with blank input*/

    const errorText = document.getElementById('enterName');
    const label = document.createElement('label');
    label.textContent = "please enter your full name";
    label.setAttribute("style", "color: red");
    if (counter == 0) {
        errorText.appendChild(label);
        counter += 1;
    }
}
});

2 个答案:

答案 0 :(得分:1)

您需要在函数外部声明counter,否则每次用户提交表单时都会重置。

let counter = 0;
form.addEventListener('submit', (e) => { /* Your awesome eventhandler */ });

这是因为JavaScript会在函数结束后删除您的变量,并在重新触发事件时重新声明它。所以它实际上重新初始化 counter

PROTIP :使用bool代替int,这样您就可以

if (messageShowed) { /* Insert some code */ }

答案 1 :(得分:0)

问题在于let counter = 0;

在事件侦听器回调之外声明它。像

 let counter = 0;
 form.addEventListener('submit', (e) => { //create new invitee name
  let text = input.value; //collect text value from input field
   ....

您的代码出了什么问题,每次事件都会触发,它会再次将counter设置为0,并附加子项。