jQuery.history

  • 4424
  • 0

摘要:jQuery.history

直接使用 ajax更新頁面不會產生瀏覽記錄,所以瀏覽器的上一頁、下一頁無法運作,把當前的網址傳給別人,也不會看到一樣的結果…略…只記錄使用方法,運作原理有點囉嗦還要考慮跨瀏覽器…不如跳過眼不見為淨XD

 


$(function(){
	//https://github.com/tkyk/jquery-history-plugin/
	$.history.cache = {};// 純粹避免重複撈同樣的資料,與 $.history無關
	$.history.init(function(hash) {
		if (hash !== '') {
			//...
			if (typeof $.history.cache[hash] == "undefined") {
				$.get(window.location.pathname + "?" + hash, handleHashChanege);
				// 後端程式原本就有接 Querystring另做處理,會把資料填好,傳回結構相似的 html
			}
			else {
				handleHashChanege($.history.cache[hash]);
			}
		}
		else {
			// 如果不是頁面上所有動作都是 Ajax,注意不要擋到 form post回來的資料
		}

		function handleHashChanege(html) {
			$.history.cache[hash] = html;
			var $html = $(html);
			// ...
			$("#contentContainer").empty().append($(html).find("#contentContainer>*"));
			/* 
			因為後端會把資料填好,傳回結構相似的 html,所以直接塞進去就好,
			跟 $(div).load(url+" $selector")效果差不多
			
			使用 empty()儘量不要綁事件在 $("#contentContainer")下的元素,以免*破舊*的瀏覽器 memory leak
			參考 jQuery.live or delegate
			*/
		};
	});
	$("#contentContainer").delegate("#main-pager a, #simple-pager a", "click", function(event) {
		event.preventDefault();
		if (this.href) {
			$.history.load(getUpdateResultUrlFromLink(this.href));
			/*
			連結直接點開也可正常運作;
			getUpdateResultUrlFromLink會統一加些額外的參數在 ajax更新畫面時使用
			*/
		};
	});
});