addEventListener - 是否有更有效的方法

时间:2015-07-17 14:31:28

标签: javascript events

我正在添加JavaScript以提醒用户他们需要填写指定的字段。这不是代码错误,但由于我有两种形式,每个字段都需要单独的JavaScript,我想知道是否有更有效的方法来编写脚本?我知道您可以在HTML中编写必需的属性,但我对此不感兴趣。

function prepareEventHandlers () {
document.getElementById("bookingFrm").addEventListener("submit",           function(event) {
        // Show message
        if (document.getElementById("email").value == "Your Email") {
            document.getElementById("errorMessage").innerHTML = "Please provide an email address!";
            // to STOP the form from submitting
            event.preventDefault(); // Prevent form from submitting // when using addEventListener, return false wont work, in all other cases use return false
        } else {
            // reset and allow the form to submit
            document.getElementById("errorMessage").innerHTML = "";
            return true;
        }  

});
}

  function prepareEventHandlersName () {
document.getElementById("bookingFrm").addEventListener("submit", function(event) {
        // Show message
        if (document.getElementById("name").value == "Your Name") {
            document.getElementById("errorMessage1").innerHTML = "Please provide a name!";
            // to STOP the form from submitting
            event.preventDefault(); // Prevent form from submitting
        } else {
            // reset and allow the form to submit
            document.getElementById("errorMessage1").innerHTML = "";
            return true;
        }          
});
}

function start() {
  prepareEventHandlers();
  prepareEventHandlersName();
}
window.onload = start;

1 个答案:

答案 0 :(得分:0)

为什么不在同一个函数中进行两次检查?

function prepareEventHandlersForBoth () {
document.getElementById("bookingFrm").addEventListener("submit", function(event) {
        // Show message
        if (document.getElementById("email").value == "Your Email") {
            document.getElementById("errorMessage").innerHTML = "Please provide an email address!";            
            event.preventDefault(); 
        } else {
            document.getElementById("errorMessage").innerHTML = "";
            return true;
        }  
        if (document.getElementById("name").value == "Your Name") {
            document.getElementById("errorMessage1").innerHTML = "Please provide a name!";
            event.preventDefault(); 
        } else {
            document.getElementById("errorMessage1").innerHTML = "";
            return true;
        }         
});
}

}

function start() {
  prepareEventHandlersForBoth();
}
window.onload = start;