这里我声明了一个函数"driverDetailsValidation";在事件侦听器中。我想从事件监听器之外调用它。这是我用过的代码,但它不起作用
driverType.onchange = function(e) {
var isWithoutDriver = (driverType.value == "without driver");
if(!isWithoutDriver){
driverDetailsValidation();
}
}
const driver_fields = document.getElementsByClassName("driver_fields");
form.addEventListener("submit", (event) => {
validity = true;
function driverDetailsValidation() {
for (let i = 0; i < driver_fields.length; i++) {
if (driver_fields[i].value == "") {
driver_fields[i].style.border = "2px solid rgb(228, 29, 22)";
driver_fields[i].style.backgroundColor = "rgba(238, 156, 156, 0.788)";
//fields[i].placeholder = "This Field is Compulsory!";
validity = false;
}
}
}
}
您可以在事件侦听器外部声明一个变量,并在侦听器内部为其分配函数。然后,您可以从如下变量调用函数:
var fct;
document.querySelector("div").addEventListener("click", function() {
fct = function() {
alert("Working");
}
});
setInterval(function() {
if (fct != null) {
fct();
fct = null;
}
}, 0);
<div>
Click me
</div>
但我认为这并没有什么意义。