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?

2 Answers 2

3

Use jQuery $(this) :

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Did you mean to type clickedItem.text() or since you're only using it once: $(this).text()?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.