views:

416

answers:

2

If I have:

<a id="anchor" href="some link" rel="{ key1: 'value', key2 : 'value'}">text</a>

How do retrieve the values in the 'rel' attribute so i can refer to them using dot notation?

eg.

$('#anchor').attr('rel').key1
A: 

Here you are giving rel the value of a stringified JSON object. You would need a JSON library and call

JSON.parse($('#anchor').attr('rel')).key1
David Hedlund
I am setting those programmatically from the server on multiple items, I suppose I could try something like: $('#<?php echo $id; ?>').data( '"Data" : { key1: 'value', key2: 'value' }' ); I think this actually makes more sense as a data setup method for populating the client with data from the server. I've been storing values in attributes until now, but using an approach like the above might actually make more sense. It would certainly make for more readable markup an code overall. Hmm.
David B
yes, `data` would be a much more appropriate place to store data. it comes with the benefits of not having to parse `JSON` back and forth, and it doesn't invalidate your markup.
David Hedlund
+1  A: 

You need a JSON deserializer or a jQuery JSON Plugin to convert the string into a JavaScript object (please don't just eval it).

var obj = JSON.parse($('#anchor').attr('rel'));

Directly attaching that object to your link with jQuery data might be an option, too.

Daff
+1 for `$.data`
David Hedlund