gpt4 book ai didi

javascript - 如何调用 HTML DOM 事件对象(例如 : onclick, onblur 等)嵌套函数?

转载 作者:行者123 更新时间:2023-11-28 19:08:11 24 4
gpt4 key购买 nike

美好的一天!假设我的页面中有一组文本字段,每个文本字段在 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 事件上调用函数内部的函数?有没有可能且更简单的方法来做到这一点?预先感谢您!

最佳答案

有很多方法可以实现这一点,但我建议使用验证库。自己开发是一个非常危险的提议,并且会导致难以管理的“意大利面条代码”。

这里有几个您可以研究的库。

http://jqueryvalidation.org

https://angularjs.org

关于javascript - 如何调用 HTML DOM 事件对象(例如 : onclick, onblur 等)嵌套函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31281702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com