jquery:how to get the id of anchor tag
I have 2 anchor tags
<li><a id="tab1" href="#tabs-1">Issue</a></li>
<li><a id="tab2" href="#tabs-2">Change Request</a></li>
I have the following jquery:
$('a').click(function(event) {
开发者_运维问答 alert($('a').attr("id"));
});
What happens: I always get "tab1" in the pop up
What I need: when user clicks on an anchor tag, its id needs to be displayed in the pop up
Your problem lies in the alert statement: with $('a')
, you aren't referencing the clicked <a>
element in the alert statement—you're retrieving the first <a>
element in the document.
Instead, to reference the clicked element, replace $('a')
with $(this)
:
$('a').click(function(event) {
alert($(this).attr("id"));
});
Try
$('a').click(function(event) {
var currentElemID = $(this).attr("id") // or you can use this.id
});
You can get any element attribute using attr() so:
$('a').attr('id');
If you only need to access the id, then using jQuery is an unnecessary overhead:
$('a').click(function(event) {
alert(this.id);
});
精彩评论