How do I serialize an javascript array into html attribute and fetch it back with jquery?
var arr=[...];
var html = '<input attr="' + serialize(arr) + '">';
I can't simply join(' ')
the arr
as there may be white space 开发者_StackOverflow社区or other special characters.
How do I do it properly?
You probably want .data
, using which you can store any data on a DOM element.
var html = $("<input>");
html.data("something", arr);
Then you can append it somewhere using the insertion methods like .append
.
Fetch the data again with:
var arr = html.data("something");
http://jsfiddle.net/UKRcs/
An alternative would be using JSON to convert things into a string and setting that as an attribute:
var html = $("<input>").attr("data-something", JSON.stringify(arr));
And the other way round:
var arr = JSON.parse(html.attr("data-something"));
http://jsfiddle.net/UKRcs/1/
You may want to look at the .data() method. This allows you to attach arbitrary objects to DOM elements.
http://api.jquery.com/data/
精彩评论