tabs 大概是網頁裡最常見的元件之一,官方與第三方實作都不少。但有朋友問起 jquery.ui.tabs 的 ajax 為何每次都還會發請求,我用 Firebug 查了官方的 ui.tabs,發現它雖然宣告了快取,每切換一次仍會向伺服器要資料——那比較像是伺服器端快取,並不等於我們想要的「只 ajax 一次」。其他外掛試下來,不是過於龐大就是過於簡單。既然如此,自己寫一個簡潔的取而代之。
功能清單:tabs 切換、自動輪播、ajax 載入。結構採用最傳統的形式:
<div id="tabs">
<ul>
<li><a href="#tabs1">tabs1</a></li>
<li><a href="#tabs2" rel="ajax.htm">tabs2</a></li>
</ul>
<div id="tabs1">Hello World!</div>
<div id="tabs2"></div>
</div>
一個 li 對應一個 div。需要 ajax 時,在 a 上加上 rel 屬性指向目標網址;內容載入後把 rel 屬性移除,此後這個分頁就走本地已寫入的內容,不再請求伺服器。這就是「只請求一次」的關鍵設計。
(本文未使用 cookie;若希望使用者關閉瀏覽器後再開啟仍是上次的分頁,可搭配 jquery.cookie 外掛記錄目前索引。)
(function ($) {
// code here
})(jQuery);
取名 aTabs,呼叫方式即為 $(...).aTabs()。
$.fn.aTabs = function (options) {
// api
// main function
};
$.fn.aTabs.defaults = {
firstOn: 0,
className: 'selected',
eventName: 'all', // click / mouseover / all
loadName: '加載中...', // ajax 等待時的提示文字
fadeIn: 'normal',
autoFade: false,
autoFadeTime: 3
};
var opts = $.extend({}, $.fn.aTabs.defaults, options);
$.extend 在此扮演關鍵角色:外部傳入的設定會覆蓋預設值,未傳的則沿用預設。
return this.each(function () { // 為每個綁定的元素各做一次
var target = $(this);
var div = target.children().not("ul,span"); // 所有內容區 div
var tabs = target.find('ul:eq(0) li'); // 所有分頁標籤
function Tabs() {
if ($(this).hasClass(opts.className)) {
return false; // 已是當前分頁,不重複處理
}
tabsShow(div, $(this));
return false; // 阻止 a 的預設跳轉
}
function tabsShow(div, li, index) {
div.stop(true, true).hide();
// 自動輪播時以索引指定
if (typeof (index) == "number") {
if (li.find("a").attr("rel")) ajax(div, li);
$(div[index]).stop(true, true).fadeIn(opts.fadeIn);
tabs.stop(true, true).removeClass(opts.className);
$(tabs[index]).stop(true, true).addClass(opts.className);
}
// 手動點擊時以 href 對應
else {
var tabBody = div.filter(li.find("a").attr("href"));
if (li.find("a").attr("rel")) ajax(div, li);
tabBody.stop(true, true).fadeIn(opts.fadeIn);
tabs.stop(true, true).removeClass(opts.className);
li.stop(true, true).addClass(opts.className);
}
}
function ajax(div, li) {
var href = li.find("a").attr("href");
var rel = li.find("a").attr("rel"); // ajax 請求網址
var i = div.filter(href); // 對應的內容區
if (rel) { // 只在 rel 存在時請求一次
i.html(opts.loadName);
$.ajax({
url: rel,
cache: false,
success: function (html) { i.html(html); },
error: function () { i.html('加載錯誤,請重試!'); }
});
li.find("a").removeAttr("rel"); // 請求過就移除,確保只 ajax 一次
}
}
if (opts.autoFade) {
var index = opts.firstOn + 1;
setInterval(function () {
if (index >= div.length) { index = 0; }
tabsShow(div, $(this), index++);
}, opts.autoFadeTime * 1000);
}
tabs.bind(opts.eventName == 'all' ? 'click mouseover' : opts.eventName, Tabs)
.filter(':first').trigger(opts.eventName == 'all' ? 'click' : opts.eventName);
});
/* 作者:黑曜石 */
(function ($) {
$.fn.aTabs = function (options) {
$.fn.aTabs.defaults = {
firstOn: 0,
className: 'selected',
eventName: 'all', // click, mouseover, all
loadName: '加載中...',
fadeIn: 'normal',
autoFade: false,
autoFadeTime: 3
};
var opts = $.extend({}, $.fn.aTabs.defaults, options);
return this.each(function () {
var target = $(this);
var div = target.children().not("ul,span");
var tabs = target.find('ul:eq(0) li');
function Tabs() {
if ($(this).hasClass(opts.className)) { return false; }
tabsShow(div, $(this));
return false;
}
function tabsShow(div, li, index) {
div.stop(true, true).hide();
if (typeof (index) == "number") {
if (li.find("a").attr("rel")) ajax(div, li);
$(div[index]).stop(true, true).fadeIn(opts.fadeIn);
tabs.stop(true, true).removeClass(opts.className);
$(tabs[index]).stop(true, true).addClass(opts.className);
} else {
var tabBody = div.filter(li.find("a").attr("href"));
if (li.find("a").attr("rel")) ajax(div, li);
tabBody.stop(true, true).fadeIn(opts.fadeIn);
tabs.stop(true, true).removeClass(opts.className);
li.stop(true, true).addClass(opts.className);
}
}
function ajax(div, li) {
var href = li.find("a").attr("href");
var rel = li.find("a").attr("rel");
var i = div.filter(href);
if (rel) {
i.html(opts.loadName);
$.ajax({
url: rel,
cache: false,
success: function (html) { i.html(html); },
error: function () { i.html('加載錯誤,請重試!'); }
});
li.find("a").removeAttr("rel");
}
}
if (opts.autoFade) {
var index = opts.firstOn + 1;
setInterval(function () {
if (index >= div.length) { index = 0; }
tabsShow(div, $(this), index++);
}, opts.autoFadeTime * 1000);
}
tabs.bind(opts.eventName == 'all' ? 'click mouseover' : opts.eventName, Tabs)
.filter(':first').trigger(opts.eventName == 'all' ? 'click' : opts.eventName);
});
};
})(jQuery);
role="tablist"、aria-selected)都還缺少,實用上可以逐步補上。自己動手寫一遍外掛,最大的收穫不是得到一個 tabs,而是把「如何用 rel 屬性做一次性載入標記」「如何封裝 defaults 讓外掛可配置」「如何處理動畫佇列競爭」這幾件事真正想通了。下次遇到 accordion、carousel,同一套骨架都能套用。