您正在创建一个函数并立即调用它,因此实际上没有将任何内容分配给变量 validateAltName - 它仍然未定义,因为这是函数的返回值。
var validateAltName = (function (info) {
var altName = $.trim(altInput.value);
console.log(altName); //only one time i am getting, not on keyup..
if (!altName) {
altInput.select();
return; // return 'undefined', which gets assigned to validateAltName
}
// if you fall off the end, it also returns 'undefined'
}()); // this _calls_ the function
删除周围的括号和尾随的 ()
var validateAltName = function (info) { // no opening paren
var altName = $.trim(altInput.value);
console.log(altName); //only one time i am getting, not on keyup..
if (!altName) {
altInput.select();
return;
}
}; // no () parens or closing )
编辑:如果你想在事件发生时向这个函数发送参数,你可以在调用它的处理程序中包含一个匿名函数:
// instead of
$(altInput).on("keyup", validateAltName); //is there a way to send parameter?
// you can use
$(altInput).on("keyup", function(e) {
// by using .call() instead of direct invocation () you can preserve 'this'
validateAltName.call(this, parm1, parm2);
}); //is there a way to send parameter?