How to store data in an attribute and then parse on click?
My end goal is to be able to send:
$('[data-track]').live('click', function () {
mpmetrics.track("Share", {'method': 'twitter'});
});
My question is how I can store the Share, method, twitter in the data-bind attribute so that they are dynamic and I can change the variables on any data-track attribute in my app.
<a data-track="XXXXXX" href="#">Tweet</a>
For XXXXXX, how can I set the 3 variables and then parse them in the data-track binding?
T开发者_JAVA百科hanks
You can store any kind of value via .data()
. Store the three values as a series of key/value pairs in an object:
$('a').data('track', { key1 : 'value1', key2 : 'value2' });
Fetch it later with
$('a').data('track');
Alternatively, just define them as three data attributes:
<a data-track="XXXXXX" data-key1="value1" data-key2="value2" href="#">Tweet</a>
And access them via .data()
:
$('a[data-track]').click(function () {
var $key1 = $(this).data('key1');
// ...
});
<a data-track="Share,method,twitter" href="#">
Then...
var dataTrack = $(this).data('track').split(','); // split by comma
var action = dataTrack[0];
var values = {};
values[dataTrack[1]] = dataTrack[2];
mpmetrics.track(action, values);
I think this should be working:
<a id="btn" href="#" data='{"method":"twitter","action":"Share"}'>Test</a>
$('#btn').click(function(){
var data = jQuery.parseJSON($(this).attr('data'));
});
精彩评论