您正在創建一個功能,並立即調用它,因此沒有實際分配到變量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?
你是正確的,但即使是KEYUP之前,我期待調用的函數..任何想法傳遞參數..?但感謝您的答案和解釋。 – 3gwebtrain