aborted
aborted

Reputation: 4541

Multiple jQuery selectors bound to the same event with a little change

I know that separating a list of selectors with a comma is actually binding multiple selectors to the same event or something else. So that's not the problem here.

The problem here is that I want to do something just a little different based on which selector was clicked.

For example I have two links:

<a href="#" data-do="add">Add</a>
<a href="#" data-do="delete">Delete</a>

Then I have a selector like this one:

$('[data-do="add"], [data-do="delete"]').click(function() {
    // do same stuff
});

For the data-do="add" I want to do a slightly different processing inside the event. Like if I could somehow ask if $(this) contains add then change something in the event and prevent the usual flow.

Just knowing how to know which link was clicked inside the event, I'd be able to do the rest with simple if statements. The problem here is that I don't know how to do this.

Any help would be appreciated.

Upvotes: 0

Views: 48

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

$('[data-do="add"], [data-do="delete"]').click(function() {
    // do same stuff

    /* you could use a simple if */
    if (this.dataset.do === 'add') {

    }

    /* or even a more complex switch */
    switch (this.dataset.do) {
       case 'add': 
          /* specific code for add */ 
          break;
       case 'delete': 
          /* specific code for delete */ 
          break;

    }
});

you could read the attribute with this.dataset.do, saving a couple of jQuery calls.

Here some performance test about data-* attribute access

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

$('[data-do="add"], [data-do="delete"]').click(function() {
    var elementType = $(this).data("do") == "add" ? "ADD":"DELETE";
    alert(elementType); //Switch by elementType
});

JS Fiddle: http://jsfiddle.net/9n8gp/

Upvotes: 0

Gromish
Gromish

Reputation: 199

$('[data-do="add"], [data-do="delete"]').click(function() {
    if ($(this)).attr("data-do") == "add"){
         // do something for add
    } 
    if ($(this)).attr("data-do") == "delete"){
         // do something for delete
    } 
});

It should also works with "data"...

$('[data-do="add"], [data-do="delete"]').click(function() {
    if ($(this)).data("do") == "add"){
         // do something for add
    } 
    if ($(this)).data("do") == "delete"){
         // do something for delete
    } 
});

Does it works? :)

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

this inside the event handler refers to the clicked element, so you can use this to refer to the clicked element

$('[data-do="add"], [data-do="delete"]').click(function () {
    //general code
    if ($(this).data('do') == 'add') {
        //something special
    }
});

Upvotes: 1

Related Questions