1

I am trying to have multiple <a> tags (or any other tag) that I want bound to the same handler. I want the handler to discover which <a> 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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lord Loh.
  • 2,437
  • 7
  • 39
  • 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,233
  • 11
  • 55
  • 86
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
  • 241,084
  • 71
  • 387
  • 401