首页 > 解决方案 > Link to open tab from menu help. jQuery Tabslet

问题描述

I'm wanting to link to a certain tab (Portfolio Tab) on a page from the main menu of a website, so when clicked it goes to that page with that portfolio tab open.

So far I've come up with this (using jQuery Tabslet) which works when not on the same page, but doesn't work if the user happens to be on the same page as the tabs, and so does nothing.

The link I use in the main menu is /about/#tab-3 which is doing the job of going to the about page with the portfolio tab open.

I thought I may need to trigger a page refresh when on the same page? And perhaps remove the #tab-3 from the url too.

Not being a jQuery expert, I unfortunately just don't know.

Here is the code so far

Thanks in advance.

jQuery(document).ready(function($){

	$('.tabs').tabslet({
		active :1,
		animation : true,
		container: '.tabs-container'
	});



	var hash = $.trim( window.location.hash );
	var anchor = $('a[href$="'+hash+'"]');

		if (anchor.length > 0){
		anchor.click();
		} 

	window.onload = function () {

		if (location.hash) {
		window.scrollTo(0, 0);
		}

	};


});

标签: javascriptjquery

解决方案


建议:始终提及您使用的插件的引用。我假设你在这里谈论这个

此插件仅对选项卡单击起作用。

因此,当像您一样在另一个页面的链接中使用窗口时hash,您必须“模拟”选项卡上的单击。

因此,您将使用属性选择器来查找具有href与哈希相对应的锚点...
并单击它。

window.onload = function () {

  if (location.hash) {
    window.scrollTo(0, 0);
    $("a[href='"+location.hash+"']").click();  // Add this!
  }
};

推荐阅读