开发者

jquery data() vs cookies

Both jQuery .data()开发者_运维问答 and browser cookies seem to do the same job saving information for later use. Is there any advantage to using one over the other? .data() seems to be quick and easy.


jQuery.data() and cookies are quite different:

  • cookies survive across requests, jQuery.data() only has the lifetime of the document it's issued in
  • jQuery.data() can store arbitrary objects, while you can only store objects serializable as text in cookies (for example, you can't directly store a DOM element in a cookie)
  • jQuery.data() is attached to a DOM element, while a cookie is attached to a domain, or a sub path of a domain

So in general jQuery.data() is used to store data used by different parts of your jQuery code (e.g. settings, cached values, etc...), and cookies are used to store persistent user information (e.g. session informations).


Data is not persistent between requests. So if you save something with .data() and then the user clicks on a link you wont have the saved data anymore (unlike cookies, which do persist).


.data() is - as Jakub already said - not persistent between requests while cookies are (you can even give them an expire time!).

However, there's another big difference: .data() is set on an element and cannot be easily retrieved without having the element (or a jQuery object containing it) while cookies are document-wide simple key=>value mappings.

Oh, and you cannot store complex data (arrays, objects) in cookies without serializing them somehow (JSON would do the job).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜