Reputation: 32370
I have a function that will be triggered on click (using jQuery).
I don't understand why the following doesn't work and shows undefined.
var testFunc = function(event) {
var data = event.data;
var category = data.category;
var action = data.action;
var label = data.label;
console.debug(data);
// prints:
// {'category': 'CCC', 'action': 'AAA', 'label': 'LLL'}
console.debug(data.category);
// prints: undefined
console.debug(category);
// prints: undefined
console.debug(data[category]);
// prints: undefined
};
$(document).ready(function() {
$('.test').on('click', function() {
var jsonData;
try {
jsonData = JSON.parse($(this).data('test'));
}
catch (e) {
// I guess here is the problem:
jsonData = $(this).data('test');
// ..but why JSON.parse doesn't work
}
try {
testFunc({ data: jsonData });
} catch (e) {
}
});
});
HTML:
<a href="about:blank" target="_blank" class="test"
data-test="{'category': 'CCC'}">click event triggered here</a>
How to access event.data.category ?
FIDDLE: http://jsfiddle.net/ytqp45wj/
Upvotes: 1
Views: 165
Reputation: 7117
To access nested object properties use []
notation, for example:
event['data']['category']
Upvotes: 0
Reputation: 13425
event.data
is a string in your fiddle.
That's because your JSON in the data-test
field is not valid.
So you pass into the exception handler when parsing it, and you use the String itself.
(Seems like you can not use single quotes in JSON, according to http://jsonlint.com/)
As pointed elsewhere, you can use double quotes inside your data attribute to fix things.
Note that the data[category]
would not work anyway, so you still get undefined
for that.
Upvotes: 2
Reputation: 3134
'use strict';
var event = {data:{
category: 'CCC',
action:'AAA',
label: 'LLL'
}};
var testFunc = function(event) {
var data = event['data'];
var category = event['data']['category'];
console.debug(data);
console.debug(category);
//get keys for every data entry
Object.keys(data).forEach(function(key){
console.log(key, data[key]);
});
};
testFunc(event);
You need to have a valid JSON object so you need to access to it using JSON notation.
Upvotes: 0
Reputation: 2519
Your JSON data isn't formatted correctly. You need to use double quotes for the key values.
<a href="about:blank" target="_blank" class="test" data-test='{"category": "CCC", "action": "AAA", "label": "LLL"}'>click event triggered here</a>
Upvotes: 2