Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json attribute

In an intranet app I have HTML elements with custom tags. There are several types of tags, data-mem is one example. In the markup it looks like this:

<a href="something.html" data-mem='{varname: "value", varname2: "value"}'>Bla Bla</a>

What I want to do is get the json attribute and use the name/value pairs in a JS method call. Note: both names and values are unknown and dynamic and I'm using jquery.

RegEvent('varname','values','varname2','value');

What I have done up till now is get the list of all tags containing a data-mem attribute:

var objs = $('a[data-mem]');

I'm a little lost now. Don't really know how to continue. Any suggestions?

Thank you!

like image 787
Elad Lachmi Avatar asked Dec 16 '22 07:12

Elad Lachmi


1 Answers

The jQuery ".data()" method does it automatically.

var data = $('#yourId').data('mem');

Then "data.varname" will be "value", etc.

edit — given your HTML, since you have not given a class or "id" to your <a> tag, I guess you could do:

var data = $('a[data-mem]').data('mem');

It might be better to find a good way to single out the element in question. It depends on the rest of the code of course.

edit again — also the JSON has to be valid - property names must be quoted.

like image 182
Pointy Avatar answered Dec 21 '22 22:12

Pointy