Why is this code repeatedly getting the first data attribute only?
HTML
<ul class="als-wrapper">
<li class="als-item"><a data-loc-subject="test value"><img src="http://www.ikea.com//us/en/images/products/pugg-wall-clock__13080_PE040801_S4.jpg" height="100" width="100"/></a>test value</li>
<li class="als-item"><a data-loc-subject="a second value"><img src="http://www.ikea.com//us/en/images/products/pugg-wall-clock__13080_PE040801_S4.jpg" height="100" width="100"/></a>a second value</li>
<li class="als-item"><a data-loc-subject="a third value"><img src="http://www.ikea.com//us/en/images/products/pugg-wall-clock__13080_PE040801_S4.jpg" height="100" width="100"/></a>a third value</li>
</ul>
jQuery
$( ".als-item" ).click(function(e) {
e.preventDefault();
var data = $('.als-item a').data('loc-subject');
alert(data);
});
You would need to use the this
context and get the data attribute for the anchor inside each list element.
Instead of
var data = $('.als-item a').data('loc-subject');
try
var data = $(this).find('a').data('loc-subject');
And use console.log for debugging purpose instead of an alert statement.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments