我有这个jQuery代码,它使用ajax检索外部内容,而无需刷新页面,并且我还有一个导航链接,当用户在当前页面上时,该链接具有不同的背景色.
jQuery代码:
function loadPage(url) //the function that loads pages via AJAX
{
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
//$('#loading').css('visibility','visible'); //show the rotating gif animation
$('.counter').html('<img src="img/ajax_load.gif" width="16" height="16" style="padding:12px" alt="loading" />');
$.ajax({ //create an ajax request to load_page.PHP
type: "POST",url: "load_page.PHP",data: 'page='+url,//with the page number as a parameter
dataType: "",//expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#change-container').html(msg); //load the returned html into pageContet
}
}
});
}
html导航代码:
<ul>
<li class="current"><a href="#page1">Home</a></li>
<li><a href="#page3">Replies</a></li>
<li><a href="#page4">Favorites</a></li>
</ul>
最佳答案
例如:http://jsfiddle.net/4cs9h/
$('ul > li > a').click(function() {
var $th = $(this).parent();
if( !$th.hasClass('current') ) {
$th.addClass('current')
.siblings('.current').removeClass('current');
loadPage(this.href);
}
return false;
});
$th变量是指父< li>. < a>中的被点击.
如果< li>如果没有当前类,则将添加该类并将其从具有该类的所有同级中删除,并将调用loadPage(),并发送被单击的< a>的href属性.
关于您的评论,是的,最好针对特定的< ul>与ID.
$('#navigation > li > a').click(function() {...
的HTML
<ul id="navigation">
<li class="current"><a href="#page1">Home</a></li>
<li><a href="#page3">Replies</a></li>
...
要使用页面中包含的哈希值,可以将其传递给loadPage()函数.
var hash = window.location.hash;
if( !hash || hash === '#' )
hash = "#page1";
loadPage( hash );