【问题标题】:how window location in javascript when localStorage but not reload page?当localStorage但不重新加载页面时,javascript中的窗口位置如何?
【发布时间】:2016-01-12 03:20:17
【问题描述】:

我将这段代码 javascript 与 localStorage 一起使用(类似于 php 中的会话)

<script>
$(function(){
        var a = localStorage.getItem('login');
        if(a=="" || a==null){window.location.href = "dash-home.html";}
        else{window.location.href = "dash-chat.html";}
    }); 
</script>

但是当定位在 dash-home.html 中时,该页面总是刷新页面(F5 重复)

【问题讨论】:

  • 重定向到dash-home时,表示用户已登录。如果是,则需要在localStorage中设置login值。
  • 设置window.location.href时,页面会刷新。
  • 我已经完成了,我问'重定向 dash-home 时总是刷新?' @Tushar
  • 确保您的“脚本”在您的“dash-home.html”中不可用,因为它是您的中立地。
  • 那么,我用什么? @fauxserious

标签: javascript jquery html local-storage


【解决方案1】:

我想你明白 AJAX / PHP 是最好的解决方案。

但是如果你不能使用AJAX,你可以使用.load()jQuery方法来模拟 AJAX。 .load() 将在您想要的时间和地点将另一个文件的内容加载到您的文档中。

例子:

if (condition == true){
    $('targetDIV').load('desired_page.html');
}

http://api.jquery.com/load/


更多关于 AJAX 的信息:

https://stackoverflow.com/a/17974843


以您为例:

<script>
    $(function(){
        var a = localStorage.getItem('login');
        if(a=="" || a==null){$('#targetDIV').load("dash-home.html");}
        else{$('#targetDIV').load("dash-chat.html");}
    }); 
</script>

<body>
    <div id="targetDIV"> This is where the other pages will appear </div>

【讨论】:

  • 为什么不只是if (condition)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 2021-07-17
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
相关资源
最近更新 更多