在 jQuery 中无需重新加载即可更改哈希

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1939041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:26:25  来源:igfitidea点击:

Change hash without reload in jQuery

jqueryhashreloadfragment-identifierwindow.location

提问by daveredfern

I have the following code:

我有以下代码:

$('ul.questions li a').click(function(event) {
    $('.tab').hide();
    $($(this).attr('href')).fadeIn('slow');
    event.preventDefault();
    window.location.hash = $(this).attr('href');
});

This simply fades a div in based on when you click but I want the page URL hash tag to change when you click so people can copy and bookmark it. At the moment this effectively reloads the page when the hash tag is change.

这只是根据您单击的时间淡入 div,但我希望页面 URL 哈希标记在您单击时更改,以便人们可以复制它并为其添加书签。目前,当哈希标签更改时,这会有效地重新加载页面。

Is it possible to change the hash tag and not reload the page to prevent the jumping effect?

是否可以更改hash标签而不重新加载页面以防止跳转效果?

回答by jitter

This works for me

这对我有用

$('ul.questions li a').click(function(event) {
    event.preventDefault();
    $('.tab').hide();
    window.location.hash = this.hash;
    $($(this).attr('href')).fadeIn('slow');
});

Check here http://jsbin.com/edicufor a demo with almost identical code

在这里查看http://jsbin.com/edicu以获取几乎相同代码的演示

回答by James Wiseman

You could try catching the onload event. And stopping the propagation dependent on some flag.

您可以尝试捕获 onload 事件。并根据某个标志停止传播。

var changeHash = false;

$('ul.questions li a').click(function(event) {
    var $this = $(this)
    $('.tab').hide();  //you can improve the speed of this selector.
    $($this.attr('href')).fadeIn('slow');
    StopEvent(event);  //notice I've changed this
    changeHash = true;
    window.location.hash = $this.attr('href');
});

$(window).onload(function(event){
    if (changeHash){
        changeHash = false;
        StopEvent(event);
    }
}

function StopEvent(event){
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

Not tested, so can't say if it would work

没有测试,所以不能说它是否有效

回答by Reza Hassani Mofrad

You can set your hash directly to URL too.

您也可以将哈希直接设置为 URL。

window.location.hash = "YourHash";

The result : http://url#YourHash

结果:http://url#YourHash

回答by Swen

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

接受的答案对我不起作用,因为我的页面在点击时轻微跳跃,弄乱了我的滚动动画。

I decided to update the entire URL using window.history.replaceStaterather than using the window.location.hashmethod. Thus circumventing the hashChange event fired by the browser.

我决定使用window.history.replaceState而不是使用window.location.hash方法更新整个 URL 。从而绕过浏览器触发的 hashChange 事件。

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

回答by Shahrukh Anwar

You can simply assign it a new value as follows,

您可以简单地为它分配一个新值,如下所示,

window.location.hash