简体   繁体   中英

append object to innerHTML and get that object from innerHTML

here is an example in jsfiddle.

I want to know if I can append a javascript object to innerHTML, that get that object again from innerHTML as object.

something like,

alert((this.innerHTML).html);

that's just an example, don't ask me why do you need this? I'm trying to edit an existing code, and I have to do this so. I have to transfer an object via div.innerHTML.

Check this jsfiddle . In it, I add the object to the div as a 'data-'-attribute, using JSON to convert it to a string. After that, adding some comment to the div triggers the DOMSubtreeModified -handler, in which the 'html'-part of the object is retrieved and alerted. It that something to work with?

In this case, quite possible your only option is to convert your object to string and then put that into the element. (This is done by looping through the key, values building the string as you go.)

You would reverse the process to convert it back into an obj.

I know some javascript libary's have helper functions to make this process very simple.

You could try adding the data directly onto the dom element, rather than as its content..

tempDiv.objData = myObject;

It was suggested to use JSON, but no code. So:

function addObjAsJSON(el, obj) {
  el.setAttribute('data-myJSON', encodeURIComponent(JSON.stringify(obj)));
}

function getObjAsJSON(el) {
  return JSON.parse(decodeURIComponent(el.getAttribute('data-myJSON')));
}

That should allow you to add anything as a serialised object, then get it back. You should add some error checking to make it robust though (eg check that you get a string back from the call to getAttribute ).

For user agents that don't have built-in JSON support, see json.org which has a link in the javascript section to json.js .

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