3

I have several different tasks that may need some optimization:

$('.container').on('click', '.one', function () {
  // do task one
});

$('.container').on('click', '.two', function () {
  // do task two
});

$('.container').on('click', '.three', function () {
  // do task three
});

Merged into the following:

$('.container').on('click', '.one, .two, .three', function () {
  // How to selectively perform each task, based on the trigger/ selector?
  // Think of if (event.type === 'mouseenter') // do sumthing
});

The question is how to selectively perform each different task, based on each trigger/ selector? Or is there a better way to perform this?

Thanks

swan
  • 2,509
  • 3
  • 24
  • 40
  • I don't get why you propose `if (event.type === 'mouseenter')` if want changes the task in your above code is the element, and not the event. You only have click events. – Diego Nov 22 '12 at 14:22
  • Just an example about selective trigger, thanks – swan Nov 22 '12 at 14:26

3 Answers3

8

A better approach may just be to chain the .on() calls:

$('.container').on('click', '.one', function () {
    // do task one
}).on('click', '.two', function () {
    // do task two
}).on('click', '.three', function () {
    // do task three
});

Doing it this way would remove the extra processing required to check whether the element has a certain class each time the event handler is triggered.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 2
    Not to mention looks far more elegant – Esailija Nov 22 '12 at 14:24
  • Like it. But the bad side is that each event not binded directly to its element has some cost. This way each time some element in container is clicked, jQuery will be asking if the element is `'.one'` or `'.two'` or `'.three'`. The only difference is that we wont see it. – Diego Nov 22 '12 at 14:28
6
$('.container').on('click', '.one, .two, .three', function () {
  if ($(this).hasClass("one")) {
    // do task one
  }
  if ($(this).hasClass("two")) {
    // do task two
  }
  if ($(this).hasClass("three")) {
    // do task three
  }
});
Diego
  • 16,436
  • 26
  • 84
  • 136
3

You can use hasClass method:

$('.container').on('click', '.one, .two, .three', function () {
  var $this = $(this);
  if ($this.hasClass('one')) {
     // 
  } else if ($this.hasClass('two')) {
     //
  } else {
    //
  }
});
Ram
  • 143,282
  • 16
  • 168
  • 197
  • 1
    If some element has more than one class this code will bahave different from the original. – Diego Nov 22 '12 at 14:23