How can I pass an entire string of data from an html element using jquery?
I need to pass data from开发者_运维问答 an HTML element and serialize it. At the moment I can do it by naming each individual attribute in the HTML tag. But It seems verbose and complicated.
<a data-type="2" data-post="101" data-parent="100">Up</a>
var myData = $(this).data("type")+$(this).data("parent")+$(this).data("post")
Can I pass all of the data with a single call instead of naming each individual attribute? For example:
var myData = $(this).data(all the attributes go here in some sort of string/serialized string)
Note: This requires jQuery 1.4.4
You could do:
var myData = $(this).data();
var str = '';
for(var i in myData) {
if(myData.hasOwnProperty(i)) {
str += myData[i];
}
}
// generates "2101100"
But note that data()
might return more then just the HTML data attributes.
DEMO
Depending on how you want to serialize the data, JSON.stringify might also be ok for you (which generates a JSON string):
var myData = $(this).data();
var str = JSON.stringify(myData);
// generates: {"type":2,"post":101,"parent":100}
DEMO
精彩评论