使用jQuery哈希来改变URL而不添加书签

希望允许用户浏览页面上的多个选项卡,但是当点击后退按钮时,返回其上一页(无需导航回其选项卡历史记录)。 感觉就像我正在使用的方法中的一个(我更改URL并处理历史记录,或者我不更改URL并且不处理历史记录)。 我查看了HTML History API,它似乎没有直接与此直接对话,也没有找到我发现的很多post。 我希望我的标签可以链接,但不能作为浏览器的单独页面(我疯了吗?)。 非常感谢你。

JavaScript的

//add tab id to url var hash = window.location.hash; hash && $('ul.nav a[href="' + hash + '"]').tab('show'); $('.nav-tabs a').click(function (e) { $(this).tab('show'); window.location.hash = this.hash; }); 

HTML

  

如果您使用jQuery ui创建选项卡,则可以使用以下命令启动选项卡:

 $( "#tabs" ).tabs({ activate: function(event, ui) { window.location.replace('#' + $(ui.newPanel).attr('id')); } }); 

这会将新单击的#添加到浏览器urkl中,而不会将其添加到历史记录中

在@Pete的帮助下,我能够使用我当前的设置(即不切换到jQuery UI)得到足够的答案。

js的第一个方面处理了在单击选项卡时创建历史记录的初始问题(感谢Pete建议使用’.replace’与’.hash =’)

 $('.nav-tabs a').click(function (e) { var myTab = $(this).tab(); window.location.replace($(myTab).attr('href')); //go to top of page instead of hashtag location window.scrollTo(0, 0); }); 

然后,如果用户输入的页面中已包含其中包含主题标签的URL,请打开相应的选项卡。

 // if window.location.hash = true, than open the tab where tab x.href == hash if(window.location.hash) { var hash = window.location.hash; $('ul.nav a[href="' + hash + '"]').tab('show'); //go to top of page instead of hashtag location window.onload = function(){ window.scrollTo(0, 0); } } 

[使用bootstrap 2 tab js]