简体   繁体   English

操作后如何重置DOM?

[英]How to reset DOM after manipulation?

My page contains some small wizard which I built using jQuery. 我的页面包含一些我使用jQuery构建的小向导。

I would like to offer the user to restart/reset the wizard and start it from the beginning level. 我想让用户重启/重置向导并从头开始启动它。

There is anyway to do it without refreshing the page? 无论如何都可以在不刷新页面的情况下执行此操作?

One way to achieve this would be to clone() the wizard's element tree in its initial state and store it in a global variable or in the document's data : 实现此目的的一种方法是将向导的元素树克隆()在其初始状态,并将其存储在全局变量或文档的数据中

$(document).data("initialWizard", $("#yourWizard").clone(true));

(Note that passing true to clone() also clones element data and event handlers, which might prove handy in your case.) (注意,将true传递给clone()也会克隆元素数据和事件处理程序,这在您的情况下可能会很方便。)

Then, when you want to restore the wizard to its original state, you can do: 然后,当您要将向导还原到其原始状态时,您可以执行以下操作:

$(document).data("initialWizard").replaceAll("#yourWizard");

The only way to start over without refreshing the page is for you to manually return the DOM to the state it was in when the page loaded and to restore any javascript state too. 在不刷新页面的情况下重新开始的唯一方法是手动将DOM返回到加载页面时的状态并恢复任何javascript状态。 You would either have to record/remember the initial state so you could go back to it or keep track of all your incremental changes so you could go back there too. 你要么必须记录/记住初始状态,所以你可以回到它或跟踪你所有的增量变化,这样你也可以回到那里。

If you really want to start over, what's wrong with a refresh? 如果你真的想重新开始,刷新有什么问题?

Similar to the above, here's what I ended up doing. 与上面类似,这就是我最终做的事情。 I stored the entire jQuery doc contents in a bootup() function (and ran it). 我将整个jQuery doc内容存储在bootup()函数中(并运行它)。 The initial contents of the body was stored in an originalDOM variable. 正文的初始内容存储在originalDOM变量中。 Then within I had a playAgain function that would set the contents of the body to that originalDOM, and run the entire jQuery contents again by calling the bootup() function. 然后在我内部有一个playAgain函数,它将body的内容设置为originalDOM,并通过调用bootup()函数再次运行整个jQuery内容。 This would all be triggered by clicking on a button of class ".startover". 这将通过单击“.startover”类的按钮来触发。

bootup();
    var bootup = function(){$(document).ready(function(){
    var originalDOM=document.body.innerHTML;
    //jQuery lines of code here
    var playAgain = function(){
        $(".startover").click(function(){
            document.body.innerHTML = originalDOM;
            bootup();
        });
    };
    playAgain();

});};

Hope that helps for anyone looking for something similar, and happy to hear feedback if there's anything I could've improved on! 希望能帮助任何寻找类似东西的人,并且很高兴听到反馈,如果有什么我可以改进的话!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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