0

单击复选框时,我正在启动一个自治功能,通过并行我将绑定事件(“keyup”)添加到同一功能,但它不起作用。而且我也无法发送参数..处理这个的正确方法是什么..?

这是我的功能:

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;
    }

}());
$(altInput).on("keyup", validateAltName); //is there a way to send parameter?
4

3 回答 3

3

您正在创建一个函数并立即调用它,因此实际上没有将任何内容分配给变量 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?
于 2013-10-31T05:47:20.097 回答
1

您正在执行您的函数并将结果存储到变量中。将您的代码更改为此

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;
    }

};
于 2013-10-31T05:47:30.807 回答
0
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;
    }
};
$(altInput).on("keyup", validateAltName);
于 2013-10-31T05:55:47.073 回答