Reputation: 4490
I want to include JavaScript object in my <a>
tag. I want my users to be able to copy and paste the html for the <a>
tag onto their site and edit it. They will also include a link to my .js
script which will process it.
Right now I have the HTML
:
<a id="test" href='#' jqueryData='{
"name":"test",
"type":"tag"
}'>Click Here</a>
And the following jQuery:
var target=$('#test');
var data= $.parseJSON(target.attr("jqueryData"));
console.log(data);
Which produces the desired output:
Object {name: "test", type: "tag"}
So it works fine, but I am always wondering if there is a better way to do this. Am I going to run into any browser support issues? I know jqueryData
is not an official attribute of <a>
...will that be a problem? Will I run into problems with special characters being in the data?
Thanks a ton for your help!
EDIT:
Thanks for the great answer(s) guys! Assuming I have 15-20 attributes to add, do you recommend approaching it with ONE jSon data like above or simply using a new attribute for each piece:
<a id="test" href='#' data-name="test" data-type="tag" data-width="100" data-test="1" .... >Click Here</a>
Upvotes: 1
Views: 133
Reputation:
You can base64 encode the object and then decode. This is perhaps not the leanest way, but it does the job. You'll need a b64 encode and decode function
<a data-json="eydkYXRhJzogJ3ZhbHVlJ30="></a>
var json = JSON.parse(b64Decode(object.getAttribute('data-json')));
Console.log(Object.keys(json));
Upvotes: 0
Reputation: 33409
Proper convention with regard to inventing your own tags is to prefix them with "data-" so something like "data-jquery-data". Then you'd need to change your code to use target.data("jquery-data")
.
Another point is that $.parseJSON throws exceptions if the string being parsed isn't JSON. So you're going to want to do something like
var data;
try {
data = $.parseJSON(target.data('jquery-data'));
} catch() {
if(data) {
console.log(data);
}
}
Other than that, I think it should be pretty okay.
Upvotes: 0
Reputation: 4061
Better use an attribute like data-jquery
. All data-
attributes are designed to add, well, additional data (it's part of the HTML5 specification). Browsers won't complain.
Just make sure to escape the code to avoid issues using escape()
, then use unescape()
before parsing the JSON.
Upvotes: 2