[英]can we declare a function inside of eventlistner and call it from outside?
Here I have declared a function "driverDetailsValidation" within the event listener.在这里,我在事件监听器中声明了一个 function “driverDetailsValidation”。 I want to call it from outside the event listener.
我想从事件侦听器外部调用它。 This is the code which I have used but it doesn't work
这是我使用的代码,但它不起作用
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;
}
}
}
}
You could declare a variable outside the event listener and assign the function to it inside the listener.您可以在事件侦听器外部声明一个变量,并在侦听器内部将 function 分配给它。 Then, you can call the function from the variable like this:
然后,您可以像这样从变量中调用 function:
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>
But it doesn't really make sense, I think.但我认为这没有任何意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.