Lord Loh.
Lord Loh.

Reputation: 2477

How do I discover the DOM element that fired the event and behave accordingly

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?

Upvotes: 1

Views: 59

Answers (2)

Barlas Apaydin
Barlas Apaydin

Reputation: 7315

Use jQuery $(this) :

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

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

Upvotes: 3

Fenton
Fenton

Reputation: 250842

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');
    }
}

Upvotes: 2

Related Questions