单击链接然后按“返回”按钮后,保持DOM更改 [英] Persisting DOM changes after clicking a link and then pressing the Back button

查看:76
本文介绍了单击链接然后按“返回”按钮后,保持DOM更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的appendTo()方法将项目附加到无序列表中。当用户单击另一个链接,然后按返回按钮时,附加的项目将消失。有没有办法使用JavaScript持久保存这些更改?

I'm using jQuery's appendTo() method to append items to an unordered list. When the user clicks another link, and then presses the Back button, the appended items disappear. Is there a way to persist those changes using JavaScript?

推荐答案

一旦用户离开您的页面,DOM就会被丢弃。当您的用户点击后退按钮时,他们会从您的服务器(或他们的缓存)获取HTML的新副本。

Once your user navigates away from your page, the DOM is discarded. When your user hits the back button, they get a fresh copy of the HTML from your server (or from their cache).

因此,您有以下两个选项之一:

So, you have one of 2 options:


  1. 正确的方法是将DOM状态保存在cookie(或会话)中,然后在页面加载时检查是否该cookie存在,如果是,请附上该信息。

  1. The correct way would be to save the DOM state in a cookie (or session), and then on page load check if that cookie is present, and if so, append that info.

由于您没有提供足够的信息,我不确定您在尝试什么去完成。因此,如果cookie不够好,您可能必须将单击事件附加到链接,而不是仅将它们发送到该链接,您将首先将DOM存储在变量 var中theDOM = $('html')。clone(true); ,然后使用AJAX请求加载该链接的HTML。

Since you have not provided enough information, I'm not exactly sure what you're trying to accomplish. So, if a cookie is not good enough, you might have to attach a click event to the link, and instead of just sending them off to that link, you'll first store the DOM in a variable var theDOM = $('html').clone(true);, and then load in the HTML for that link with an AJAX request.

您还必须通知浏览器您的历史记录状态已更改。这可以通过HTML5的新History API来实现。在较旧的浏览器中,您可以通过URL的哈希部分执行类似的操作(尽管在IE的旧版本中甚至不起作用)。然后,当用户单击后退按钮时,您将从变量中重新加载该DOM ...

You'll also have to inform the browser that your history state has changed. That can be accomplished with HTML5's new History API. In older browsers you can do something similar via the hash part of the URL (although in older versions of IE even that won't work). Then, when the user clicks the back button, you'll reload that DOM from your variable...

无论哪种方式,这都太复杂了。你可能正在以错误的方式看待这个问题。你想要完成什么?

Either way, this is WAY too complicated. You're probably looking at this the wrong way. What are you trying to accomplish?

这篇关于单击链接然后按“返回”按钮后,保持DOM更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆