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

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

问题描述

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



如何让所需页面不会刷新到默认页面?



JavaScript:

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

HTML:

 < nav class =navbar navbar-defaultrole =navigation> 
< div class =container-fluid>

< div class =collapse navbar-collapseid =bs-example-navbar-collapse-1>
< ul class =nav navbar-nav>
< li>< a href =id =show_one>一个< / A>< /锂>
< li>< a href =id =show_two>两< / A>< /锂>
< li>< a href =id =show_three>三个< / A>< /锂>
< / ul>

< ul class =nav navbar-nav navbar-right>
< a data-toggle =modaldata-target =#myModal>模态对话框< / a>
< / ul>
< / div>
< / div>
< / nav>


< div class =container>
< div class =modal fadeid =myModaltabindex = - 1role =dialogaria-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 =buttonid =show_one1class =btn btn-infodata-dismiss =modalaria-hidden =true> One< / button>
< button type =buttonid =show_two2class =btn btn-infodata-dismiss =modalaria-hidden =true> Two< / button>
< button type =buttonid =show_three3class =btn btn-infodata-dismiss =modalaria-hidden =true>三< / 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>


解决方案

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



工作示例



- http://codepen.io/nitishdhar/pen/DGHkw



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



详细解释

首先您可以像这样改进处理展示的方式 -



您可以将一个常用类添加到您希望将页面更改事件从其中更改为的所有链接/按钮触发器&在它们中存储一个数据属性,定义他们应该打开哪个页面,如下所示 -



链接

 < li>< a href =#class =show-pagedata-page =one>一个< / A>< /锂> 
< li>< a href =#class =show-pagedata-page =two>两< / A>< /锂>
< li>< a href =#class =show-pagedata-page =three>三个< / A>< /锂>

注意class&我添加的数据页面属性。此外,我给了一个#href,这样你就不必在点击事件时返回false。你也可以使用javascript:void(0);而不是#如果你不希望你的窗口哈希得到更新。



对于按钮

 < button type =buttonclass =btn btn-info show-page modal-btndata-page =onedata-dismiss =modal aria-hidden =true>一个< /按钮> 
< button type =buttonclass =btn btn-info show-page modal-btndata-page =twodata-dismiss =modalaria-hidden =true> Two< ; /按钮>
< button type =buttonclass =btn btn-info show-page modal-btndata-page =threedata-dismiss =modalaria-hidden =true> Three< ; /按钮>

我也添加了一个modal-btn类到模态内渲染的按钮。这是为了处理模态隐藏事件,仅适用于模态中的按钮。这是没有必要附加模态('隐藏')的其他链接。



现在在您的JavaScript使它工作,你会做这样的事情 -


$ b $

  $('。show-page')。click(function(){
/ * Get Page to Show * /
var pageToShow = $(this).data('page');
/ *先隐藏所有页面* /
$('。page')。addClass('hide');
/ *显示链接被点击的页面* /
$('。'+ pageToShow).removeClass('hide');
});

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

因此,我们试图绑定每个具有class show-page的元素的click事件。然后单击我们读取该特定点击元素的数据页面属性中的内容。然后,我们隐藏所有页面&只显示持有人被点击的人。这样您就不必为所有按钮编写单独的事件处理程序。



我也在分别处理隐藏模式。



使用会话存储



现在会话存储是浏览器存储,它将为您保留当前会话的一些数据,关闭浏览器窗口。



我们将保留一个变量,用于保存用户以前的最后一页,像这样 -

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

现在,当用户尝试移动到页面时点击事件,我们将保留更新会话变量'pageToShow',像这样 -

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

现在,如果用户还刷新页面,我们将首先检查是否在会话中设置了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天全站免登陆