我正在构建基于ajax的导航,一切都运行良好,除了一个问题:
当我在Firebug中查看时,每次单击时都会调用并加载ajax站点两次。
这是脚本:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the main and show the progress bar
$('#main').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
//AJAX Navigation Helper function
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
//AJAX Navigation Helper function
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the main retrieved from ajax and put it in the #main div
$('#main').html(html);
//display the body with fadeIn transition
$('#main').fadeIn('slow');
//reload site scripts
$.getScript("js/script.js");
}
});
}
每当我点击导航栏中的列表时,页面会正常加载到#main,但它会发生两次(在Firebug中显示)。有没有人知道为什么?
我注意到当我通过URL访问某个页面时不会发生这种情况(只会进行一次ajax调用),所以我猜问题可能出现在click函数中。
附注:我正在使用jquery历史插件,但我不认为问题出现在那里,是吗?
getPage
被调用了多少次,以及为什么被调用了多少次? - user166390