【发布时间】:2015-07-08 09:38:15
【问题描述】:
美好的一天! 假设我的页面中有一组文本字段,每个文本字段在 onblur 期间都有自己的验证,例如数量文本字段,如果我移除它的焦点,它会检查它是否大于 100,000。
<input type = "text" id = "amount" placeholder="Amount" onblur="validateAmount()">
function validateAmount(){
var amount = document.getElementById("amount").value;
if (amount > 100000){
document.getElementById("errormessage").innerHTML = "Invalid! Enter a number less than 100,000!"; //Let's just assume that I have a label for the error message
}
}
哎呀!这只是具有验证的文本字段之一,如果我有 5 个,假设我单击按钮来处理在我的验证中有 3 个问题的数据,因此不会因为这些错误而处理数据。在我的例子中,我将使用 onclick 事件,看看这个例子:
<button onclick = "checkData()"> Apply </button>
function checkData(){
//Here in checkData() method/function, I want to put the validateAmount() function above and other functions of validation during onblur to count and state the number of errors before submitting the data.
var numberOfErrors = 0;
function validateAmount(){
var amount = document.getElementById("amount").value;
if (amount > 100000){
document.getElementById("errormessage").innerHTML = "Invalid! Enter a number less than 100,000!"; //Let's just assume that I have a label for the error message
numberOfErrors++;
}
}
/* And more validating functions here
*/
// After validating all the textfields.
if(numberOfErrors == 0){
alert("Congrats! You already submitted the loan");
} else {
alert("Error! Check your inputs!");
}
}
所以我的问题是如何在 HTML DOM 事件上调用函数内部的函数?有没有可能和更简单的方法来做到这一点?提前谢谢!
【问题讨论】:
标签: javascript html events dom nested-function