Can I run jQuery function and on load and on change?

人盡茶涼 提交于 2020-05-11 05:12:08

问题


I want to run a script on page load first time (for default value of select element), and then on each change of select element. Is it possible to do it in one line, or do I need to duplicate function for this events?

I know that I can use next structure:

$('#element').on('keyup keypress blur change', function() {
    ...
});

But it doesn't seem to support load event.

Any ideas?


回答1:


If i understand what you mean, just trigger any one of these events:

$('#element').on('keyup keypress blur change', function() {
    ...
}).triggerHandler('keyup'); //or trigger('keyup') or keyup() which then let event propagate



回答2:


for change element use your :

$('#element').on('change', function() {
    ...
});

and to use same function on load first time use structure like:

jQuery(window).on("load", function(){

  $('#element').change();

});

to call the same function




回答3:


Instead of using anonymous functions (defining them right where they will be used) you could just create a regular function and tell jQuery to call it when those events happen.

$(document).ready(myFunction);
$('#element').on('keyup keypress blur change', myFunction);

function myFunction() {
    // Do something here...
}


来源:https://stackoverflow.com/questions/17922981/can-i-run-jquery-function-and-on-load-and-on-change

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