Reputation: 575
I have a element defined as follows:
<span class="road-btn js-road-btn" data-lat-s=' + row.LatL + ' data-lng-s=' + row.LongL + ' data-lat-e=' + row.LatD + ' data-lng-e=' + row.LongD +'> <i class="icon-pin"></i ></span >
I have performed a click event on this element as :
$('.js-road-btn').on('click', function () {
var latS = $(this).attr('data-lat-s');
var longS = $(this).attr('data-lng-s');
var latE = $(this).attr('data-lat-e');
var longE = $(this).attr('data-lng-e');
});
Instead of getting each attribute separately, I want to retrieve all the attributes values as a whole. Then I access the properties separaretly. How can I achieve this in jquery ?
Upvotes: 2
Views: 7365
Reputation: 67505
You could use the jQuery method .data()
like :
$(this).data(); //Will return the set of all the data-* attributes
$('.js-road-btn').on('click', function() {
var attributes = $(this).data();
console.log(attributes);
alert(attributes.lngE);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="road-btn js-road-btn" data-lat-s='1' data-lng-s='2' data-lat-e='3' data-lng-e='4'> Click me </span >
Upvotes: 4
Reputation: 337560
As the values are all stored in data-*
attributes, you can use data()
(with no arguments) to retrieve them all in a single object:
$('.js-road-btn').on('click', function() {
var data = $(this).data();
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="road-btn js-road-btn" data-lat-s="lat-s" data-lng-s="lng-s" data-lat-e="lat-e" data-lng-e="lng-e">
Click me
</span>
Upvotes: 2