Reputation: 51
On a page I have multiple links all with a tracking code attached. The tracking code is different on every link. When I click on a link I want to select the tracking code attached to that href. If I just use
$('.bannerLink').attr('data-trackingcode')
It'll just select the first link rather than the one I click on. How do I select the one I just clicked on
<div class="container">
<div>
<a href="someLink" class="bannerLink" data-trackingcode="trackingCodeA">
<img src="//someImage.jpg" alt="Cereals">
</a></div></div>
<div class="container">
<div>
<a href="someLink" class="bannerLink" data-trackingcode="trackingCodeB">
<img src="//someImage.jpg" alt="Cereals">
</a></div></div>
<div class="container">
<div>
<a href="someLink" class="bannerLink" data-trackingcode="trackingCodeC">
<img src="//someImage.jpg" alt="Cereals">
</a></div></div>
Upvotes: 2
Views: 37
Reputation: 337560
You can use the this
keyword to reference the clicked element within the click event handler function. Try this:
$('.bannerLink').click(function() {
var trackingCode = $(this).data('trackingcode');
});
Note the use of data()
to access the data-*
attribute is preferred over attr()
.
Upvotes: 3
Reputation: 4945
$(document).on('click','.bannerLink',function() {
$(this).attr('trackingcode')
});
Upvotes: 0