jQuery .on keyup 和模糊仅在加载时触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16654133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:31:56  来源:igfitidea点击:

jQuery .on keyup and blur firing onload only

jqueryjquery-on

提问by Mooseman

Problem: The blurand keyupevents each fire once onload, and only onload. How can I get them to work correctly?

jQuery:

问题:blurkeyup事件每个都在加载时触发,并且仅在加载时触发。我怎样才能让它们正常工作?

jQuery:

function myFunction(text){
    alert(text);
}
$('#input1').on({
    keyup: myFunction('keyup'),
    blur: myFunction('blur'),
    focus: function(){console.log('focus!');}
});

Fiddle: http://jsfiddle.net/GrMQX/

小提琴:http: //jsfiddle.net/GrMQX/

回答by Claudio Redi

You are not assigning a function to keyupand blur, you're assigning the result of the execution of myFunction.

您没有将函数分配给keyupand blur,而是将 的执行结果分配给myFunction

Change it like this:

像这样改变它:

$('#input1').on({
    keyup: function() { myFunction('keyup'); },
    blur:  function() { myFunction('blur'); },
    focus: function() { console.log('focus!'); }
});

DEMO

演示

回答by Nick Andriopoulos

You're not declaring the functions as callbacks, you're executing them and their return result is assigned as a callback (which doens't work).

您没有将函数声明为回调,而是执行它们,并且它们的返回结果被分配为回调(这不起作用)。

Try this:

尝试这个:

  $('#input1').on({
    keyup: function() { myFunction('keyup') },
    blur: function() { myFunction('blur') },
    focus: function(){console.log('focus!');}
  });

回答by Gabriele Petrioli

You need to pass a function as an argument.. you are passing the return value of the called function

您需要将函数作为参数传递.. 您正在传递被调用函数的返回值

function myFunction(text){
    alert(text);
}
$('#input1').on({
    keyup: function(){myFunction('keyup');},
    blur: function(){myFunction('blur');},
    focus: function(){console.log('focus!');}
});


Or you can convert your myFunctionto a function generator

或者您可以将您的转换myFunction为函数生成器

function myFunction(text){
   return function(){
       console.log(text);
   }
}

$('#input1').on({
    keyup: myFunction('keyup'),
    blur: myFunction('blur'),
    focus: function(){console.log('focus!');}
});

Demo athttp://jsfiddle.net/gaby/GrMQX/6/

演示在http://jsfiddle.net/gaby/GrMQX/6/

回答by j08691

You're actually executing the functions when you call them that way. Try this:

当您以这种方式调用它们时,您实际上是在执行它们。尝试这个:

$('#input1').on({
    keyup: function(){myFunction('keyup')},
    blur: function(){myFunction('blur')},
    focus: function(){console.log('focus!');}
});

jsFiddle example

jsFiddle 示例

回答by Yasir Aslam

use with .on() Event

与 .on() 事件一起使用

$(document).on("keyup blur", "#input1", function(event)
    {       
    // your code        

    });