window.location.hash在页面重新加载后变空

时间:2016-06-06 09:48:38

标签: javascript jquery

我是JavaScript新手。我有一个Django应用程序,其中包含URL标签。单击每个选项卡后,页面将重新加载。为了在页面重新加载后保持选定的选项卡处于活动状态,我将在window.location.hash中存储URL的属性,然后在页面重新加载期间读取该属性以访问所选选项卡。

我的代码(部分):

HTML

<div class="col-xs-6">
    <ul class="nav nav-tabs" role="tablist" id="demoTabs">
        <li class="nav-item">
            <a data-url="/tab1/" href="{% url '...' %}" class="nav-link" role="tab">
                <small>...</small>
            </a>
        </li>
        <li class="nav-item">
            <a data-url="/tab2/" href="{% url '...' %}" class="nav-link" role="tab">
                <small>...</small>
            </a>
        </li>

JS代码

$(function() {

    var hash = window.location.hash;
    $('ul.nav a[data-url="' + hash + '"]').tab('show');
    alert(window.location.hash);

    $('#demoTabs li a').click(function(e) {
        window.location.hash = $(this).attr('data-url');
        alert("HASH: " + window.location.hash);
    });
});

&#34; HASH:&#34; alert正确显示哈希值(#/tab1/#/tab2/),但第一个警报显示为空白。如何防止window.location.hash的值在页面重新加载时被清除?请帮忙!

1 个答案:

答案 0 :(得分:0)

而不是使用..

window.location.hash = $(this).attr('data-url')

使用..

window.location.href += "#" + $(this).attr('data-url');

然后location.reload()

$(function() {
  var hash = window.location.hash;
  //$('ul.nav a[data-url="' + hash + '"]').tab('show');
  alert(window.location.hash);

  $('#demoTabs li a').click(function(e) {
    window.location.href += "#" + $(this).attr('data-url');
    alert(window.location.hash);
    location.reload();
  });
});
相关问题