我有这个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>
因此,基本上,当有人单击“答复”链接时,我希望li类更改为current,以表明您在该页面上.
最佳答案
例如: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 );
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。