开发者

What is the correct way to store data in the DOM

I have recently been using the title tag in various HTML elements to store data in JSON format in the DOM.

Is this a bad approach (I am assuming it is)? What is the correct way to accomplish this that works well with jQuery? By "works well" I mean

$("myButton").click(function 开发者_StackOverflow中文版(e) {
     var myData;
     eval("myData=" + $(this).attr("title"));
});

Works pretty well but again I am assuming there is a better way to do this no?

PS: BTW how does the title tag of HTML elements actually work? I cant seem to find where it actually ends up getting used?

PSS: Can I also get a jQuery based and Non jQuery response? (Sorry to be fussy)


eval("myData=" + $(this).attr("title"));

This is almost a legal reason to slap you! (j/k)

You should use your own namespace object to store data "globally". In that context, globally means only global in your application code and not using the global object (window in a browser).

var my_application = {};

$('myButton').click(function() {
  my_application.myData = $(this).attr('title');
});

This is a very basic strategy of course. In your particular case, you can also use jQuery's .data() method to attach data to a DOM node.

$('myButton').click(function() {
   $.data(this, 'myData', this.title);
});

Ref.: .data(), jQuery.data()


In your example, I'd suggest doing the following which does not expose you to the security risks of 'eval':

myData = JSON.decode($(this).attr("title"));

In general it's a valid approach to holding non-secure data. You have a number of other options too:

  • Use JQuery's .data() methods:

    myData = $this.data("foo");

  • In HTML5 you now can use custom data attributes (Eg "") as an attribute on any element. http://html5doctor.com/html5-custom-data-attributes/

  • You could use Local Storage if you know it is available. http://dev.w3.org/html5/webstorage/

  • You could use Backbone.js on top of Jquery to give you a more abstracted way of handling your data as Models. http://documentcloud.github.com/backbone/


use jquery data()

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later:

jQuery.data(document.body, 'foo', 52);


In the jQuery world it is usually said to be a best practice to use the metadata plugin as it is an official jQuery plugin and also supports HTML5 data attributes. For more info you could look at this http://docs.jquery.com/Plugins/Metadata/metadata

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜