开发者

How to invoke same code using multiple events?

开发者 https://www.devze.com 2023-03-13 03:37 出处:网络
I have the following code .. $(\"#input_name\").blur(function(){ //more code }开发者_JS百科); It works fine, but now I need to invoke the same functionality as in the blur function above by clickin

I have the following code ..

$("#input_name").blur(function(){
  //more code
}开发者_JS百科);

It works fine, but now I need to invoke the same functionality as in the blur function above by clicking a button as well. Basically, I want to keep the blur as is, and add the onclick. Any ideas how do I do that? Thanks


You can do this:

$("#input_name").bind("blur click", function() { ... });

You can also separate the function definition from the binding:

function handler() { ... }

$('#input_name').blur(handler).click(handler);

Remember that jQuery will pass the event to the handler function, and you can check the event type:

function handler(ev) {
  if (ev.type === 'click') { ... }


Change your function definition to not be inline and then reuse it.

function eventFunction(){
    //more code
}

$('#input_name').blur(eventFunction);
$('#button_name').click(eventFunction);


Place "//more code" in a function:

function more_code() {
    //more code
}

and call it from your handlers:

$("#input_name").blur(more_code)
0

精彩评论

暂无评论...
验证码 换一张
取 消