[英]onBlur Event Function Fires on Pageload in Vanila Javascript
I have a basic validation function and a addEventListener
to attach to a select
element.我有一个基本的验证函数和一个
addEventListener
来附加到一个select
元素。 Now, not only doesn't the function fire when during the event, but it fires on pageload
.现在,该函数不仅不会在事件期间触发,而且会在
pageload
时触发。 Can you please help me figure out why?你能帮我弄清楚为什么吗?
The element is:元素是:
<select name="VisitSchedLocation" id="VisitSchedLocation" size="1">
<option value="">Choose a location for this visit</option>
<option value="1">Location 1</option>
...
</select>
The addEventListener
is: addEventListener
是:
document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation());
And, finally, the function :最后,函数:
function validateVisitSchedLocation() {
if (VisitSchedLocation.options[VisitSchedLocation.selectedIndex].value == '') {
alert('Location must be selected!');
return false;
};
}
Any help would be greatly appreciated.任何帮助将不胜感激。
You are calling/invoking the function rather than attaching it to event:您正在调用/调用该函数,而不是将其附加到事件:
document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation());
Instead do this ( No parentheses ):而是这样做(无括号):
document.getElementById('VisitSchedLocation').addEventListener('blur', validateVisitSchedLocation);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.