Pavel Pavel - 7 months ago 16
Javascript Question

Jquery onClick event and multi event data for same classes

How can extract in Jquery "data" value from this:

<a href="#" data="12" class="virus">12</a>
<a href="#" data="123" class="virus">another but no 123</a>
<a href="#" data="124" class="virus">need number from data=""</a>


to onClick event from each of these anchor with same classes? Thank you:).

Answer

$('.virus').click(function() {


  alert($(this).attr('data'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data="12" class="virus">12</a>
<a href="#" data="123" class="virus">another but no 123</a>
<a href="#" data="124" class="virus">need number from data=""</a>

use : .attr()

Description: Get the value of an attribute for the first element in the set of matched elements.

I suggest you make the data="12" into something like data-data="12" since data is not a valid attr.

Using .data()

Description: Store arbitrary data associated with the matched elements.

Then you can get it like

$(this).data('data')