jQuery UI Tabs or .load() - tab links in different container than tab content and append URL
I have the following html strucuture
<div id-"top">
<ul id="tabs">
<li><a href="#tab-content-1">tab 1</a></li>
<li><a href="#tab-content-开发者_开发知识库2">tab 2</a></li>
<li><a href="#tab-content-3">tab 3</a></li>
</ul>
<!--/top--></div>
<div id="content">
<div id="tab-content-1">content 1</div>
<div id="tab-content-2">content 2</div>
<div id="tab-content-3">content 3</div>
<!--/bottom--></div>
From what I can see and in other uses, jQuery UI tabs requires the ul and the content to be in the same container, which mine aren't.
So I went with the .load() function - I changed the link's from "#tab-content-1" to "AjaxPages/tab-content-1.html" respectively for this method, and have the following code that works, but I can't get it to append the url so it would reflect the visible content so they are bookmarkable and able to be linked to directly.
$(function() {
$('#content').load('AjaxPages/tab-content-1.html');
});
$("#tabs li a").click(function(e) {
e.preventDefault();
var $parent = $(this).parent();
$parent.addClass("selected").siblings().removeClass("selected");
var href = $(this).attr('href');
$("#content").load(href);
});
I can add the div id to the url with basic jQuery UI tabs with this:
if($(".tab-set") && document.location.hash){
$.scrollTo(".tab-set");
}
$(".tab-set ul").localScroll({
duration:300,
hash:true
});
with the localScroll and scrollTo plugins. Any advice? this shouldn't be this hard!
I made a jsfiddle but can't test it entirely because you can't handle hashes from the address bar, at least clicking a link works as expected, hope it helps.
HTML
<div id="top">
<ul id="tabs">
<li><a href="#1">tab 1</a></li>
<li><a href="#2">tab 2</a></li>
<li><a href="#3">tab 3</a></li>
</ul>
</div><!--/top-->
<div id="content"></div><!--/bottom-->
JS
$(function() {
function loadContentTroughHash(hash) {
var orighash = hash ? hash : window.location.hash;
var h =
orighash.length > 1
&& orighash.indexOf('#') != -1
&& !isNaN(orighash.substring(1))
? orighash.substring(1)
: 1;
// hash is not just '#' but has '#' and hashtag is a number
// else use 1
$('#content').load('AjaxPages/tab-content-'+h+'.html');
}
$("#tabs li a").click( function(e) {
e.preventDefault();
var $t = $(this),
$parent = $t.parent(),
href = $t.attr('href');
$parent.addClass("selected").siblings().removeClass("selected");
loadContentTroughHash(href);
});
loadContentTroughHash();
});
精彩评论