In your document ready handler, you can examine the value of the fragment and use JavaScript to show the corresponding tab.
$(document).ready(function () {
...
var tabId = window.location.hash; // will look something like "#h-02"
$(tabId).click(); // after you've bound your click listener
});
Edit as requested:
$(document).ready(function() {
$(".tab-content").hide();
$("ul.tabs li:first").addClass("active").show();
$(".tab-content:first").show();
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active");
$(this).addClass("active");
$(".tab-content").hide();
var activeTab = $(this).find("a").attr("href");
$(activeTab).show();
return false;
});
$(window.location.hash).click(); // super-simple, no? :)
});?
Edit 2:
If you want to be able to specify an ID of a tab content element (like h-02
in the page you linked) then you have to work backwards to get the ID of the corresponding tab to activate it. Like this:
$(document).ready(function() {
var $tabContent = $(".tab-content"),
$tabs = $("ul.tabs li"),
tabId;
$tabContent.hide();
$("ul.tabs li:first").addClass("active").show();
$tabContent.first().show();
$tabs.click(function() {
var $this = $(this);
$tabs.removeClass("active");
$this.addClass("active");
$tabContent.hide();
var activeTab = $this.find("a").attr("href");
$(activeTab).show();
return false;
});
// Grab the ID of the .tab-content that the hash is referring to
tabId = $(window.location.hash).closest('.tab-content').attr('id');
// Find the anchor element to "click", and click it
$tabs.find('a[href=#' + tabId + ']').click();
});?
Using $.closest()
means that the hash can specify the ID of the .tab-content
itself (such as tabs-commenters
in your example), or a child thereof.
I've made some other cleanup suggestions as well above. No need to keep re-selecting those DOM elements!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…