sierra.charli3
sierra.charli3

Reputation: 225

List of data- attribute to pass values with jQuery

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

Answers (3)

NightsWatch
NightsWatch

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

antyrat
antyrat

Reputation: 27765

Use this instead of selector:

var data = $(this).data('loc');

jsFiddle

Upvotes: 1

Guruprasad J Rao
Guruprasad J Rao

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);
});

DEMO

Upvotes: 1

Related Questions