var asign = function(id){
return document.getElementById(id) ;
} ;
var f_name = asign('fname').value ;
var validate = function (a) {
this.a = a ;
if(!a){
alert("Somthing is require");
} else if(a.length<6){
alert("characters should be minimum 6") ;
}
}
asign('submit').addEventListener('click',validate(f_name),false) ;
在页面刷新中验证函数调用,点击按钮后没有任何事情发生验证函数没有发生
答案 0 :(得分:1)
您需要在addEventListener
中将函数作为参数传递给参数,但不要调用它,
1 。您可以将代码包装成像这样的功能
asign('submit').addEventListener('click', function () {
validate();
}, false);
2 。或使用.bind
asign('submit').addEventListener('click', validate.bind({}), false);
实施例
var asign = function(id) {
return document.getElementById(id);
};
var validate = function () {
var a = asign('fname').value;
if (!a) {
alert("Somthing is require");
} else if (a.length < 6) {
alert("characters should be minimum 6");
}
}
asign('submit').addEventListener('click', validate.bind({}), false);
<input id="fname">
<button id="submit">submit</button>