我确定我错过了一些明显的东西,但知道为什么下面的 addEventListener 代码到处都在触发(不仅仅是在提交按钮上)?
HTML:
<form action="#">
<input type="text"><br>
<input type="text"><br>
<button id="submit">submit</button><br>
</form>
JS:
function validate () {
var inputs = document.getElementsByTagName('input');
var inputs_length = inputs.length-1;
for (i=0; i<=inputs_length; i++) {
var inputs_value = document.getElementsByTagName('input')[i].value;
if (inputs_value == "") {
alert('there is a text box empty');
}
}
}
var el = document.getElementById('submit');
if (el.addEventListener) {
el = addEventListener('click', validate, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', validate);
}
修复就是改变
el = addEventListener('click', validate, false);
到
el.addEventListener('click', validate, false);
我的错字:(