1

I am trying to have multiple tags (or any other tag) that I want bound to the same handler. I want the handler to discover which tag was clicked and behave accordingly.

example:

<a class="menu">Item1<a>
<a class="menu">Item2<a>
<a class="menu">Item3<a>

$(".menu").click(function(){
    //...Find out which a was clicked...
    ($(a .menu).html()=='Item1)

}

What is the best way to go about doing this? I want this to behave in a way similar to the VirtualHosts section of Apache. Is it even possible to do this?

Lord Loh.
  • 2,397
  • 5
  • 36
  • 64

2 Answers2

3

Use jQuery $(this) :

$(".menu").click(function(){
    $(this).html('Item1');
}

here is difference with jQuery: What's the difference between '$(this)' and 'this'?

Community
  • 1
  • 1
Barlas Apaydin
  • 7,125
  • 11
  • 54
  • 84
2

The this keyword will be the element that triggered the event:

$(".menu").click(function(){
    var clickedItem = this;
    alert(clickedItem.innerHTML);
}

You can wrap that in a jQuery object if you like:

$(".menu").click(function(){
    var clickedItem = $(this);
    if (clickedItem.text() === 'Item1') {
        alert('It was item 1');
    }
}
Fenton
  • 224,347
  • 65
  • 373
  • 385