我有这个 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>
没有 current
类,该类将被添加并从具有该类的任何 sibling 中删除,并且loadPage()
将被调用,发送 href
单击的属性 <a>
.
关于您的评论,是的,针对特定的 <ul>
是个好主意有身份证。
$('#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 );
关于jquery - CSS 和 jQuery 当前链接导航 : how to update the <li> class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851341/