在jQuery中更改哈希而不重新加载

时间:2022-09-11 15:16:32

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?

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

4 个解决方案

#1


71  

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/edicu for a demo with almost identical code

点击http://jsbin.com/edicu查看代码几乎相同的演示

#2


4  

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

没有经过测试,所以不能说是否可行

#3


0  

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.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

我决定使用window.history.replaceState更新整个URL,而不是使用window.location.hash方法。因此绕过了浏览器触发的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);
        }
    }
});

#4


0  

You can simply assign it a new value as follows,

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

window.location.hash

#1


71  

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/edicu for a demo with almost identical code

点击http://jsbin.com/edicu查看代码几乎相同的演示

#2


4  

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

没有经过测试,所以不能说是否可行

#3


0  

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.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

我决定使用window.history.replaceState更新整个URL,而不是使用window.location.hash方法。因此绕过了浏览器触发的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);
        }
    }
});

#4


0  

You can simply assign it a new value as follows,

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

window.location.hash