I would like to build a tracking system for a Web-based Application built in CakePHP 2.x. The idea is to have all the tracked link having written as below:
<a
href="#"
class="track-click"
data-tracking='{
"trackers": [
{
"tracker": "----",
"eventId": "---",
"tracking_options": {
"eventTargetUrl": "---",
"props": [{
"key": "----",
"value": "---"
}]
}
}
]
}'
/>
The javascript that handles the track requests should be able to gather the information that resides inside the data-tracking attribute. This would be done by attaching a click event on the "track-click" class onClick event.
Below is how I use the link above:
$('.track-click').click(function(e){
//Lets grab the data thats within the data-tracking attribute and do something with it
var data = $(this).attr('data-tracking');
alert(data.trackers);
e.preventDefault();
});
At this present moment if I alert the above I get undefined. If I put $(this).attr('data-tracking').val() on my code I get the error below:
TypeError: $(...).attr(...).val is not a function
What is the best way of manipulating links that have a json data as shown above?
-
1Did you try closing in HTML the last attribute (data-tracking) with single quote, ' ? It seems not to be closed.javifm– javifm2015年04月20日 10:23:14 +00:00Commented Apr 20, 2015 at 10:23
-
Close your a tag and put single quote at the end of this string.Sumit– Sumit2015年04月20日 10:24:15 +00:00Commented Apr 20, 2015 at 10:24
1 Answer 1
You need to use
var data = JSON.parse($(this).attr('data-tracking'));
This will return you the object.
Else you must use
var data = $(this).data('tracking');
.data() will return you the object. whereas .attr() will stringify and return that object.