2009-12-21 79 views
43

我有以下代码:变化哈希jQuery中

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

这只是变淡一个div基于当你点击,但我想要的网页URL哈希标签更改当您单击让人们可以复制并为其添加书签。目前,当散列标签发生变化时,这会有效地重新加载页面。

是否可以更改哈希标记并且不重新加载页面以防止跳跃效应?

+1

我跑这个当前页面上的下面,才正是你想要的(没有重新加载页面):$( “A”)点击(函数(事件){event.preventDefault();窗口。 location.hash = $(this).attr('href');})。也许在你的代码运行的时候,页面还没有加载?检查中有多少项目在'$(“ul.questions李一”)' – 2009-12-21 09:49:48

回答

70

这对我的作品在这里http://jsbin.com/edicu

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

检查演示几乎相同的代码

+0

你好,是的,它不会起作用,但是当页面滚动时的散列链接改变它跳转到div。 – daveredfern 2009-12-21 11:50:01

+0

检查修改过的代码。如果你不想发生这种情况,你只需要切换最后两行。原来的顺序是你的,我一直是这样,因为我认为这就是你想要的 – jitter 2009-12-21 12:05:33

+0

谢谢:)做的工作很棒。 – daveredfern 2009-12-21 16:01:13

4

您可以尝试捕获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; 
    } 
} 

没有测试过,所以不能说是否会工作

+1

一个,你需要将本地变量“事件”传递到“StopEvent” – 2009-12-21 09:43:50

+0

哎呀。谢谢相应编辑。 – 2009-12-21 10:30:42

+0

感谢您的支持将会带给您一个旋风。 – daveredfern 2009-12-21 11:50:41

0

接受的答案不适合我,因为我的网页在点击时略微跳跃,搞乱了我的滚动动画。

我决定使用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); 
     } 
    } 
});