问题
I manipulated a webpage DOM via some js libraries which altered the behaviour of onMouseup
onMousedown
and onMousemove
, among other things which I can't be sure of.
Using a DOM inspector I could see that some of these changes are set as properties of the main "document" object.
So, what I am trying to figure out is a way to store, when the page is loaded, the initial state of the "document" object (or probably store the entire DOM?) so that later I will be able to restore it.
My naive attempt at this:
var initial_state = document
document = initial_state
Guess what? It didn't work... So... what do I need to know and how could I do it right?
UPDATE: I am aware now that java assignment is by reference and not by values so now I am now experimenting with .extend(), but the main point of this question is on wheter or not, by any means, I will be able to save the full state of the DOM at its initial stage (when page is received) and then restore it at a second time. By full state I mean html, javascript state, object properties and methods so that when you restore it, the DOM is exactly the same as the one you received first time.
I understand that this can be difficult and can require case specific code directly proportional to the complexity of the javascript code state. But it would help and I would be extremely grateful if I could see at least a code example for doing it the right way in the simplest of the cases (as in my question example case, where you receive some html and just some js that changes default values for onMousedown for the whole document).
回答1:
Because how JavaScript works (objects are not copied but passed by reference) initial_state
var has just stored the reference to the DOM document. When the DOM document is updated your initial_state
var will reflect those changes because it's just a reference which is just pointing at the DOM document, and not an object "on its own".
To obtain a copy of an object which is a "real" object and not just a reference to the first object, you need to clone.
If you use jQuery you can clone by using extend function
// for simple cloning
var initDoc = $.extend({}, document);
// for deep cloning
var initDocument = $.extend(true, {}, document);
If you are not interested in using jQuery.extend() please take a look this related question on cloning object in JavaScript.
How do I correctly clone a JavaScript object?
来源:https://stackoverflow.com/questions/19149917/how-to-reset-dom-state-to-the-initial-state-when-page-was-firstly-received