简体   繁体   English

如何在页面刷新时保留 javascript/jquery 对 DOM 所做的更改

[英]How to keep the changes made to DOM by javascript/jquery on page refresh

My problem is when I click a link (example Second Page ) it will display a second page on screen.我的问题是当我点击一个链接(例如Second Page )时,它会在屏幕上显示第二页。 But when I reload the page, the current page is not saved and it revert to the default page.但是当我重新加载页面时,当前页面没有保存,而是恢复到默认页面。

How do I keep the desired page from refreshing to the default page?如何防止所需页面刷新到默认页面?

JavaScript: JavaScript:

<script type="text/javascript"> 
    $(function(){
        $('.one').show();
        $('.two').hide();
        $('.three').hide();
        $('#show_one, #show_one1').click(function(){
            $('.one').show();
            $('.two').hide();
            $('.three').hide();
            $('.modal').modal('hide');
            return false;
        });
        $('#show_two, #show_two2').click(function(){
            $('.one').hide();
            $('.two').show();
            $('.three').hide();
            $('.modal').modal('hide');
            return false;
        });
        $('#show_three, #show_three3').click(function(){
            $('.one').hide();
            $('.two').hide();
            $('.three').show();
            $('.modal').modal('hide');
            return false;
        });
    });
</script>

HTML: HTML:

<nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="" id="show_one"> One</a></li>
                <li><a href="" id="show_two"> Two</a></li>
                <li><a href="" id="show_three"> Three</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <a data-toggle="modal" data-target="#myModal"> Modal Dialog</a>
            </ul>
        </div>
        </div>
    </nav>


<div class="container">
                <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-body">
                                <form class="form-horizontal">
                                    <div class="form-group">
                                        <div class="col-sm-offset-2 col-sm-10">
                                            <button type="button" id="show_one1" class="btn btn-info" data-dismiss="modal" aria-hidden="true">One</button>
                                            <button type="button" id="show_two2" class="btn btn-info" data-dismiss="modal" aria-hidden="true">Two</button>
                                            <button type="button" id="show_three3" class="btn btn-info" data-dismiss="modal" aria-hidden="true">Three</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
</div>

<div class="container">
        <div class="one">
            <div class="row">
                <center>
                    Page 1
                </center>
             </div>
        </div>
        <div class="two">
            <div class="row">
                <center>
                    Page 2
                </center>
             </div>
        </div>
        <div class="three">
            <div class="row">
                <center>
                    Page 3
                </center>
             </div>
        </div>
</div>

When you change the state of your DOM using javascript, it will reset to the actual state on page reload.当您使用 javascript 更改 DOM 的状态时,它将在页面重新加载时重置为实际状态。 If you want to be able to store this state & present the DOM in the same state on reload, you will have to use either localStorage or sessionStorage .如果您希望能够存储此状态并在重新加载时以相同状态显示 DOM,则必须使用localStorage 或 sessionStorage In this case I will use sessionStorage to show you how this can be done.在这种情况下,我将使用 sessionStorage 向您展示如何做到这一点。 You can read about the difference here - http://www.w3schools.com/html/html5_webstorage.asp您可以在此处阅读差异 - http://www.w3schools.com/html/html5_webstorage.asp

Working Example工作示例

A full working example of how this can be achieved is here - http://codepen.io/nitishdhar/pen/DGHkw如何实现这一点的完整工作示例在这里 - http://codepen.io/nitishdhar/pen/DGHkw

You can switch to some page & then refresh your browser window & it will stay on that page only.您可以切换到某个页面,然后刷新浏览器窗口,它只会停留在该页面上。

Detailed Explanation详细说明

First of all the way you are handling the show can be improved like this -首先,您处理节目的方式可以像这样改进-

You can just add one common class to all the links/buttons from which you want the page change event to trigger & store a data attribute in them defining which page they should open if clicked, something like this -您只需将一个通用类添加到您希望页面更改事件触发的所有链接/按钮中,并在其中存储数据属性,定义单击时应打开哪个页面,如下所示 -

For Links对于链接

<li><a href="#" class="show-page" data-page="one"> One</a></li>
<li><a href="#" class="show-page" data-page="two"> Two</a></li>
<li><a href="#" class="show-page" data-page="three"> Three</a></li>

Notice the class & data-page attribute I added.注意我添加的 class & data-page 属性。 Also I gave a # to the href, this way you won't have to return false on click event.我还给href 加了一个#,这样你就不必在点击事件时返回false。 You may also use javascript:void(0);你也可以使用 javascript:void(0); instead of # if you don't want your window hash to get updated.而不是 # 如果你不希望你的窗口哈希得到更新。

For buttons also对于按钮也

<button type="button" class="btn btn-info show-page modal-btn" data-page="one" data-dismiss="modal" aria-hidden="true">One</button>
<button type="button" class="btn btn-info show-page modal-btn" data-page="two" data-dismiss="modal" aria-hidden="true">Two</button>
<button type="button" class="btn btn-info show-page modal-btn" data-page="three" data-dismiss="modal" aria-hidden="true">Three</button>

I have also added a modal-btn class only to the buttons that render inside the modal.我还仅向在模态内呈现的按钮添加了一个 modal-btn 类。 This is to handle the modal hide event only for the buttons that are in the modal.这是为了仅处理模态中的按钮的模态隐藏事件。 It is unnecessary to attach modal('hide') to the other links.没有必要将 modal('hide') 附加到其他链接。

Now in your javascript to make it work, you will do something like this -现在在你的 javascript 中让它工作,你会做这样的事情 -

$('.show-page').click(function(){
   /* Get the Page to Show */
   var pageToShow = $(this).data('page');
   /* Hide all pages first */
    $('.page').addClass('hide');
   /* Show the page whose link was clicked */
    $('.' + pageToShow).removeClass('hide');
 });

$('.modal-btn').click(function() {
    $('.modal').modal('hide');
});

So we are trying to bind the click event of every element that has class show-page.所以我们试图绑定每个具有类 show-page 的元素的点击事件。 Then on click we read what's in that specific clicked element's data-page attribute.然后点击我们读取特定点击元素的数据页面属性中的内容。 Then we hide all pages & show only the one whose holder was clicked.然后我们隐藏所有页面并仅显示其持有人被点击的页面。 This way you don't have to write separate event handlers for all buttons.这样您就不必为所有按钮编写单独的事件处理程序。

I am also handling hiding of modal separately.我也在单独处理模态的隐藏。

Using Session Storage使用会话存储

Now session storage is browser storage that will hold some data for you for the current session ie until user closes the browser window.现在会话存储是浏览器存储,它将为您保存当前会话的一些数据,即直到用户关闭浏览器窗口。

We will maintain a variable that will hold the last page user was at before, something like this -我们将维护一个变量来保存用户之前所在的最后一页,就像这样 -

/* Check if session has some page to show stored */
if(typeof(Storage)!== "undefined" && sessionStorage.getItem('pageToShow')) {
    var pageToShow = sessionStorage.getItem('pageToShow');
    /* Hide all pages first */
     $('.page').addClass('hide');
    /* Show the page whose link was clicked */
     $('.' + pageToShow).removeClass('hide');
    /* Also set this page to session storage */
     sessionStorage.setItem('pageToShow', pageToShow);
}

Now on click events when user tries to move to a page, we will keep updating the session variable 'pageToShow', something like this -现在,在用户尝试移动到页面时的点击事件中,我们将不断更新会话变量“pageToShow”,如下所示 -

$('.show-page').click(function(){
    /* Get the Page to Show */
    var pageToShow = $(this).data('page');
    /* Hide all pages first */
     $('.page').addClass('hide');
    /* Show the page whose link was clicked */
     $('.' + pageToShow).removeClass('hide');
     if(typeof(Storage)!=="undefined") {
        sessionStorage.setItem('pageToShow', pageToShow);
    }
});

Now if user refreshes the page also, we will first check if we have a pageToShow set in session & if we do, we will move to that page, just like you wanted.现在,如果用户也刷新页面,我们将首先检查是否在会话中设置了 pageToShow,如果设置了,我们将移动到该页面,就像您想要的那样。

Note: You can use localStorage instead of sesstionStorage if you want the pageToShow variable to stay even after user closes & reopens the browser later.注意:如果您希望 pageToShow 变量在用户关闭并稍后重新打开浏览器后保持不变,您可以使用 localStorage 而不是 sesstionStorage。

将所有内容都设置为<a href="javascript:void(0)"> ,您就大功告成了。

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

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