开发者

Two elements using the same event function

What is the best way to share one function开发者_高级运维 between two different event handlers? I want the same outcome but some situation dependent variables will need to be defined within the function depending on which element was clicked.

I could hack a solution but want to know the best practice for such a scenario. Simple problem must have a simple answer.

EXAMPLE

var onMyEvent = function(e){
    if(click triggered from 'a'){
        //do that 
    }  
    if(click triggered from 'div'){
        //do that
    } 
}


$('a').click(onMyEvent);
$('div').click(onMyEvent);

FIDDLE: http://jsfiddle.net/f6C92/


I guess there'd be several ways to achieve this, such as checking the e variable for target objects, etc, but for your scenario, the easiest and most readable would be using the is() function, to which you can pass any CSS selector to test if the object of interest matches it.

var onMyEvent = function(e){
    if($(this).is('a')){
        //do that 
    }  
    if($(this).is('div')){
        //do that
    } 
}


$('a').click(onMyEvent);
$('div').click(onMyEvent);

There are those who would argue that the above takes an unnecessary round-trip to jQuery, when you could achieve the same by testing this.tagName == 'A', but I usually recommend to delegate these things to jQuery as well, for browser compatibility reasons.

Another neat way would be to pass the relevant information as event data:

var onMyEvent = function(e){
    if(e.data.type == 'a'){
        //do that 
    }  
    ...
}


$('a').click({ type: 'a' }, onMyEvent);
$('div').click({ type: 'div' }, onMyEvent);


It depends how complicated the differences are, but I don't really like checking element type in the handler. I would probably do something like this:

function doSomething(...){
  // do stuff
}


$('a').click(function(){
   // set some variables and send them as parameters to doSomething
   doSomething(...);
});

$('div').click(function(){
   // set some variables and send them as parameters to doSomething
   doSomething(...);
});

Where doSomething contains the common code.


The target property of the event will contain the element that was clicked. In this updated fiddle, I alert the id of the clicked element, using e.target.id.


This ought to do the trick:

var onMyEvent = function(e) {
    if (this.tagName == "A") {
       alert("a");   
    } else if (this.tagName == "DIV") {
        alert("div"); 
    }
}


var onMyEvent = function(e){
    if(this.tagName == 'A'){
       alert("a");
    }  
    if(this.tagName == 'DIV'){
       alert("div");
    } 
}

$('a').click(onMyEvent);
$('div').click(onMyEvent);

Even if this will work in my opinion it's better to set a different handler for each tag, and call the same function inside it, like kingjiv suggested

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜