简体   繁体   中英

get jquery.data() related to an element from a saved html using javascript or jquery

I have some html that I want to save in database for a later retrieve.

Let's imagine the html is a simple div

<div id="mydiv">This is my div</div>

I use jQuery.data() to store some information related to that div like this :

$("#mydiv").data("divNumber", "5").data("divRole", "adminMessage") .....

Then finally I save the html in database, but I would like to be able to get those information later when I need them :

var myHtml = { here I get the html from my database }

$("body").append(myHtml);

console.log( $("#mydiv").data("divNumber") ); // I want it to show 5

console.log( $("#mydiv").data("divRole") ); // I want it to show adminMessag

from my understanding of jquery.data() I think it will just store those data information temporary in an internal cache and if I save the html in the database, and I leave the page, they will be lost !!

So is there a way to keep those jquery.data() information and retrieve them whenever I want ? or maybe there is another "better" way to achieve the same thing (I am not looking for localStorage method)

You can convert the .data() to data attributes on the html and save that.

 $("#mydiv").data("divNumber", "5").data("divRole", "adminMessage"); $.each($("#mydiv").data(), function(k,v){ $("#mydiv").attr("data-"+k.replace(/[AZ]/g, "-$&"), v); }); var toDatabase = $("#mydiv")[0].outerHTML; //save to database // ... // retrieve from database var fromDatabase = $(toDatabase); $('body').append(fromDatabase.data('divNumber')); $('body').append('<br>'); $('body').append(fromDatabase.data('divRole')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mydiv">This is my div</div> 

If you want to have a database in the browser which works across all platforms consistently, despite each browser having different underlying storage mechanisms try PouchDB. It is great! You can keep it just in your browser session which will persist until the user clears their data OR you can have it persist to a CouchDB database server.

http://pouchdb.com/

There are many good CouchDB providers if you dont want to setup your own although that is simple to do. IBM Cloudant is free until your usage is above $50 per month:

https://cloudant.com/

It is very simple to use, see here . A couple lines of code to create a db object and a few to put / fetch. Then one line each to setup a remote copy and one line to live sync to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM