且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将DOM状态重置为初始状态(页首首次收到?)

更新时间:2023-01-31 20:30:08

因为JavaScript如何工作(对象不被复制,而是通过引用传递) code> initial_state var刚刚存储了对DOM文档的引用。当DOM文档更新时,您的 initial_state var将反映这些更改,因为它只是指向DOM文档的引用,而不是自己的对象。



要获取作为真实对象的对象的副本,而不仅仅是对第一个对象的引用,您需要克隆



如果您使用jQuery,可以使用扩展功能

  //用于简单克隆
var initDoc = $ .extend({} ,文件);

//深入克隆
var initDocument = $ .extend(true,{},document);

如果您不想使用jQuery.extend(),请查看有关克隆的相关问题



如何正确克隆JavaScript对象?


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).

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?