jQuery .on keyup and blur firing onload only

一个人想着一个人 提交于 2019-12-03 13:18:54

问题


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

jQuery:

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

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


回答1:


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

Change it like this:

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

DEMO




回答2:


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!');}
  });



回答3:


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 myFunction to a function generator

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

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

Demo at http://jsfiddle.net/gaby/GrMQX/6/




回答4:


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




回答5:


use with .on() Event

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

    });


来源:https://stackoverflow.com/questions/16654133/jquery-on-keyup-and-blur-firing-onload-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!