Reputation: 655
I have a lot of elements that have the same tags as follow:
<ul>
<li>
<a>1</a>
...
</li>
<li>
<a>2</a>
...
</li>
<li>
<a>3</a>
...
</li>
...
</ul>
User can click on any element. How can I detect the element that user click? (I don't know the number of element before. I can be five or there or any number).
Thanks
Upvotes: 1
Views: 55
Reputation: 148130
You can use $(this)
or this
to refer to source of event.
$('a').click(function(){
alert($(this).text());
alert(this.innerText);
});
It is better to use a class
to be specific, so that the event is bind with intended elements instead of any a on the page. You can assign a class to elements on which you want to bind click event and use class selector to bind the event.
<a class="myclass">1</a>
$('.myclass').click(function(){
alert($(this).text());
alert(this.innerText);
});
Upvotes: 4
Reputation: 3302
You can get the clicked element using this
. For example:
$('a').click(function(){
alert($(this).text()); //displays the clicked element's text.
});
Upvotes: 3
Reputation: 123739
Binding on anchor tag
$('ul li a').on('click',function(){
alert($(this).text()); //This will give the text
alert(this.id); //This will give you the id if you have id for anch tag.
});
Binding on li
$('ul li').on('click',function(){
alert($(this).text()); //This will give the text of anchor ta in your case
alert($(this).index()); //This will give you the index of li with respect to its siblings.
});
Upvotes: 1