如何在页面刷新时保留 javascript/jquery 对 DOM 所做的更改 [英] How to keep the changes made to DOM by javascript/jquery on page refresh

查看:29
本文介绍了如何在页面刷新时保留 javascript/jquery 对 DOM 所做的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是当我点击一个链接(例如第二页)时,它会在屏幕上显示第二页.但是当我重新加载页面时,当前页面没有保存,而是恢复到默认页面.

如何防止想要的页面刷新到默认页面?

JavaScript:

HTML:

</nav><div class="容器"><div class="modalfade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-body"><form class="form-horizo​​ntal"><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">一个</button><button type="button" id="show_two2" class="btn btn-info" data-dismiss="modal" aria-hidden="true">两个</button><button type="button" id="show_three3" class="btn btn-info" data-dismiss="modal" aria-hidden="true">三</button>

</表单>

<div class="容器"><div class="one"><div class="row"><中心>第 1 页</中心>

<div class="two"><div class="row"><中心>第2页</中心>

<div class="三"><div class="row"><中心>第 3 页</中心>

解决方案

当您使用 javascript 更改 DOM 的状态时,它会在页面重新加载时重置为实际状态.如果您希望能够存储此状态 &在重新加载时以相同状态呈现 DOM,您必须使用 localStorage 或 sessionStorage.在这种情况下,我将使用 sessionStorage 向您展示如何做到这一点.您可以在此处阅读差异 - http://www.w3schools.com/html/html5_webstorage.asp

工作示例

这里有一个完整的工作示例,说明如何实现这一点 - http://codepen.io/nitishdhar/pen/DGHkw

您可以切换到某个页面&然后刷新您的浏览器窗口 &它只会停留在那个页面上.

详细说明

首先你处理节目的方式可以像这样改进 -

您只需将一个通用类添加到您希望页面更改事件触发的所有链接/按钮中 &在它们中存储一个数据属性,定义点击时应该打开哪个页面,就像这样 -

链接

  • 一个</a></li><li><a href="#" class="show-page" data-page="two">两个</a></li><li><a href="#" class="show-page" data-page="three">三个</a></li>
  • 注意类 &我添加的数据页属性.我也给了一个# 给href,这样你就不必在点击事件时返回false.你也可以使用 javascript:void(0);而不是 # 如果你不希望你的窗口哈希得到更新.

    对于按钮也

    <button type="button" class="btn btn-info show-page modal-btn" data-page="one" data-dismiss="modal" aria-hidden="true">一个<button type="button" class="btn btn-info show-page modal-btn" data-page="two" data-dismiss="modal" aria-hidden="true">两个</button><button type="button" class="btn btn-info show-page modal-btn" data-page="three" data-dismiss="modal" aria-hidden="true">三</button>

    我还仅向在模态内呈现的按钮添加了模态-btn 类.这是为了仅处理模态中的按钮的模态隐藏事件.没有必要将 modal('hide') 附加到其他链接.

    现在在你的 javascript 中让它工作,你会做这样的事情 -

    $('.show-page').click(function(){/* 获取要显示的页面 */var pageToShow = $(this).data('page');/* 首先隐藏所有页面 */$('.page').addClass('隐藏');/* 显示链接被点击的页面 */$('.' + pageToShow).removeClass('隐藏');});$('.modal-btn').click(function() {$('.modal').modal('隐藏');});

    所以我们试图绑定每个具有类 show-page 的元素的点击事件.然后在单击时我们读取特定单击元素的 data-page 属性中的内容.然后我们隐藏所有页面 &仅显示其持有人被点击的那个.这样您就不必为所有按钮编写单独的事件处理程序.

    我也在单独处理模态的隐藏.

    使用会话存储

    现在会话存储是浏览器存储,它将为您保存当前会话的一些数据,即直到用户关闭浏览器窗口.

    我们将维护一个变量来保存用户之前所在的最后一页,就像这样 -

    /* 检查会话是否有一些页面来显示存储的 */if(typeof(Storage)!== "undefined" && sessionStorage.getItem('pageToShow')) {var pageToShow = sessionStorage.getItem('pageToShow');/* 首先隐藏所有页面 */$('.page').addClass('隐藏');/* 显示链接被点击的页面 */$('.' + pageToShow).removeClass('隐藏');/* 同时将此页面设置为会话存储 */sessionStorage.setItem('pageToShow', pageToShow);}

    现在当用户试图移动到一个页面时的点击事件,我们将不断更新会话变量pageToShow",就像这样 -

    $('.show-page').click(function(){/* 获取要显示的页面 */var pageToShow = $(this).data('page');/* 首先隐藏所有页面 */$('.page').addClass('隐藏');/* 显示链接被点击的页面 */$('.' + pageToShow).removeClass('隐藏');if(typeof(Storage)!=="undefined") {sessionStorage.setItem('pageToShow', pageToShow);}});

    现在如果用户也刷新页面,我们将首先检查我们是否在 session & 中设置了 pageToShow如果我们这样做,我们将转到该页面,就像您想要的那样.

    注意:如果您希望 pageToShow 变量在用户关闭后保持不变,您可以使用 localStorage 而不是 sesstionStorage &稍后重新打开浏览器.

    My problem is when I click a link (example Second Page) it will display a second page on screen. 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:

    <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:

    <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. 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. In this case I will use sessionStorage to show you how this can be done. You can read about the difference here - 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

    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. Also I gave a # to the href, this way you won't have to return false on click event. You may also use 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. 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.

    Now in your javascript to make it work, you will do something like this -

    $('.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. 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 i.e 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 -

    $('.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.

    Note: You can use localStorage instead of sesstionStorage if you want the pageToShow variable to stay even after user closes & reopens the browser later.

    这篇关于如何在页面刷新时保留 javascript/jquery 对 DOM 所做的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    前端开发最新文章
    热门教程
    热门工具
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆