Reputation: 225
I've got a list of data attribute, however, the jquery only gets the first list value, when click second or third "test", the alert only shows "house". http://jsfiddle.net/ar1bd4bj/2/
<ul class="list">
<li>
<a data-loc="house" href="#">test</a>
</li>
<li>
<a data-loc="house-2" href="#">test</a>
</li>
<li>
<a data-loc="house-3" href="#">test</a>
</li>
</ul>
<script>
$( "ul.list li > a" ).click(function(e) {
e.preventDefault();
var data = $('ul.list li > a').data('loc');
window.location.hash = (data);
alert(data);
});
</script>
Upvotes: 1
Views: 542
Reputation: 467
your current code always picks first matching element and showing the result, I have modified the code to pick the data from element clicked.
$( "ul.list li > a" ).click(function(e) {
e.preventDefault();
var data = $(e.target).attr('data-loc');
window.location.hash = (data);
alert(data);
});
Upvotes: 0
Reputation: 29683
Use $(this)
to refer to the current clicked element
$( "ul.list li > a" ).click(function(e) {
e.preventDefault();
var data = $(this).data('loc'); //here
window.location.hash = (data);
alert(data);
});
Upvotes: 1