程式庫提供 Tip 函式接受訊息字串參數,而 TagToTip 函式則允許你提供元素的識別名稱以顯示其 HTML 的內容。這兩個函式的用法都相當簡單,在此就不再贅述,本文將會側重在兩者的併用,並透過範例逐步說明告訴你,如何結合 jQuery 的應用來動態載入伺服器所提供的提示訊息。
在以下的範例網頁片段中,你會看到座位平面圖,以及其所組成映射區域,並且繫結要實作動態提示訊息的 onmouseover 事件處理函式。
<img src="Images/seatingplan.png" usemap="#seatingPlan" />
<map name="seatingPlan">
<area shape="rect" id="Front Stalls" coords="22,100,493,236"
onmouseover="showSectionInfo(this, 61);" />
<area shape="rect" id="Rear Stalls" coords="22,252,492,388"
onmouseover="showSectionInfo(this, 62);" />
</map>
在定義 onmouseover 事件處理函式之前,我們先在 jQuery 的 DOM ready 事件中,預先建立一個供資料讀取的過程中顯示處理訊息的隱藏區塊,並將 Tooltips 程式庫中的 UnTip 函式繫結所有映射區域元素的 onmouseout 事件處理常式。
$(document).ready(function() {
    $('<div></div>')
    .attr('id', 'ajaxLoading')
    .html('Loading...')
    .hide()
    .appendTo('body');
    $("map[name='seatingPlan'] *")
    .mouseout(UnTip);
});當映射區域元素 onmouseover 事件被觸發時,將會執行以下函式並將所接收的傳遞參數做為請求參數,來進行遠端呼叫:
function showSectionInfo(element, sectionId) {
    if (data(element) === undefined) {
        tooltip.call(element, 'ajaxLoading');
        $.ajax({
            url: 'InfoHandler.ashx',
            type: 'GET',
            data: {
                id: sectionId
            },
            dataType: 'html',
            error: function(xhr) {
                UnTip();
                alert('The ajax request failed.');
            },
            success: function(response) {
                data(element, response);
                tooltip.call(element);
            }
        });
    } else {
        tooltip.call(element);
    }
}在叫用 jQuery 的 ajax 函式處理非同步請求前,會先透過以下所定義的 tooltip 函式叫用 TagToTip 函式將先前所建立的隱藏訊息顯示出來,以回應使用者的請求:
function tooltip(elementId) {
    var options = [ABOVE, true, SHADOW, true];
    if (elementId === undefined) {
        Tip.apply(this, $.merge([data(this)], options));
    } else {
        TagToTip.apply(this, $.merge([elementId], options));
    }
}當 AJAX 請求成功後,會透過如下的 data 函式將回應結果暫存到元素物件中,提供給後續可能的相同觸發動作讀取之用,以避免冗餘的資料請求。
function data(element, value) {
    return value === undefined ? $.data(element, 'tooltip') :
        $.data(element, 'tooltip', value);
}最後,再次呼叫 tooltip 函式將回應結果委由 Tip 函式顯示出來。
 
0 comments :: Using DHTML Tooltips with AJAX
張貼留言