首页 > 解决方案 > 如何防止外部函数的默认值而不是事件监听器?

问题描述

我有这个事件监听器,提交表单。

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();使用外部功能?

标签: javascript

解决方案


只需将事件传递给另一个函数:

//...
validateActualTemp(inputs[i].value,inputs[i],e)
//...


function validateActualTemp(value, item,e) {
    if(value === '10') {
        e.preventDefault();
        item.style.backgroundColor = 'red';
        console.log(item);
    }
}

或者从您的验证函数返回真/假,并在事件处理程序回调中处理其他所有内容。


推荐阅读