javascript - 如何防止外部函数的默认值而不是事件监听器?
问题描述
我有这个事件监听器,提交表单。
document.getElementById("form").addEventListener("submit", (e) => {
const inputs = document.querySelectorAll('#form input');
// Check for empty fields
if ([...inputs].some(input => !input.value)) {
e.preventDefault(); // Prevent form submitted until all fields are not empty
}
for (var i = 0; i < inputs.length; i++) {
// Validate specific inputs - where "name" starts with "actual-temp"
if(inputs[i].name.startsWith("actual-temp")) {
validateActualTemp(inputs[i].value, inputs[i]); // This is another function to check values
}
}
});
在这个事件监听器之后,我有这个功能:
function validateActualTemp(value, item) {
if(value === '10') {
item.style.backgroundColor = 'red';
console.log(item);
}
}
这将验证输入字段 - 并检查是否显示了数字。我现在需要做的是,如果value === '10'
然后停止提交表单,即使所有字段都已填写。
我试过这个:
function validateActualTemp(value, item) {
if(value === '10') {
preventDefault();
item.style.backgroundColor = 'red';
console.log(item);
}
}
但它不起作用 - 我怎样才能preventDefault();
使用外部功能?
解决方案
只需将事件传递给另一个函数:
//...
validateActualTemp(inputs[i].value,inputs[i],e)
//...
function validateActualTemp(value, item,e) {
if(value === '10') {
e.preventDefault();
item.style.backgroundColor = 'red';
console.log(item);
}
}
或者从您的验证函数返回真/假,并在事件处理程序回调中处理其他所有内容。
推荐阅读
- php - 使用 PHP 将 SQL 表从一个数据库复制到不同服务器上的数据库
- java - 系统未调用 Android NotificationListenerService#onNotificationRemoved(..., int reason)
- java - 如何在Java中找到小数点的差异
- python - 循环列表并根据索引创建字典
- laravel - 如何在 laravel 5.2 中使用 ckeditor 上传图片?
- c# - 如何在asp.net mvc中限制用户在没有会话的情况下一次又一次地提交联系表单
- prestashop - 在 prestashop 1.7 中输入错误的 url 时如何直接重定向到 404 错误页面?
- c# - 从 Web 客户端调用 Microsoft Bot Framework 机器人,无需在 Azure 上托管
- animation - Aframe 通过 event-component & proxy-component 触发 Element 的动画
- python - python的概率论:均值,标准差