Storing arbitrary data in HTML

What is the best way to embed data in html elements for future reference?

As an example, suppose we have jQuery returning some JSON from the server, and we want to upload this file to the user in the form of paragraphs. However, we want to be able to attach metadata to these elements so that we can events for them later.

How do I deal with this with some ugly prefix

function handle_response(data) { var html = ''; for (var i in data) { html += '<p id="prefix_' + data[i].id + '">' + data[i].message + '</p>'; } jQuery('#log').html(html).find('p').click(function(){ alert('The ID is: ' + $(this).attr('id').substr(7)); }); } 

Alternatively, you can build the form in a paragraph and save your metadata there. But that often seems redundant.

This was asked in different ways, but I do not feel that he answered well:

+4
source share
5 answers

HTML5 now supports data-name syntax for storing incompatible data without custom attributes

This will, of course, break the check if your doctype is something other than HTML5 (although there are ways around this), but it will not affect the rendering or parsing in any browsers I came across.

Here is a great article by John Rezig on this subject

+6
source

Assuming you stay on the page ...

jQuery has a data function that allows you to store data by element by key. eg,

 $('#mydiv').data('mykey', mydata); 

Use the following syntax to retrieve data:

 var x = $('#mydiv').data('mykey'); 

If you don't know which element to use, just use $(document)

+2
source

depending on what the metadata is for, you can start adding classes to paragraphs:

 <p class="some-paragraph meta meta2 meta3"> 

This should not adversely affect the style of your page if there are no collisions between metadata and existing CSS classes.

+1
source

One of the methods that I usually use (instead of HTML5 data) is to use hidden input tags, for example.

 <a href="#" id="containing_element"> Content <input type="hidden" id="key" value="value" /> </a> 

Then, if you don't mind the jQuery example.

 $('a#containing_element').click(function(){ var data = $(this).children('input#key').attr('value'); }); 

Simple, it checks, it works now , and you can use it to store any information that you like (even arrays if you serialize them and htmlencode them)

+1
source

As an alternative to the other methods mentioned, if you want to exclude IE6 (around this time), you can use the DOM repository (i.e. globalStorage , sessionStorage and localStorage ) to store your JSON string. These objects are repositories of key values, therefore, if the browsers you are targeting support support this function (part of the HTML5 specifications), then this is probably easier than storing data in arbitrary HTML elements. See here for more details.

+1
source

Source: https://habr.com/ru/post/1308871/


All Articles