[英]CSS and jQuery current links navigation: how to update the <li> class
我有這個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
類更改為當前,以表明您在該頁面。
示例: 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
變量引用被點擊的<a>
的父<li>
。
如果<li>
不具有current
類,類將被添加,並且將來自具有類任何兄弟姐妹被移除,並且loadPage()
將被調用,發送href
被點擊的屬性<a>
。
關於你的評論,是的,用一個ID來定位特定的<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 );
這將適用於您想要的,有限制:
$('ul a').click(
function(){
$('.current').removeClass('current');
$(this).addClass('current');
return false;
}
);
問題是:
ul
沒有id
,所以這個 (推測導航) ul
與頁面上的任何其他內容沒有區別, ul
任何鏈接( a
),該鏈接將獲得current
類名。 這可能是你想要的,但我不推薦它,它太容易導致不必要的行為。 給父級ul
一個id
(這是在頁面上唯一標識的方式),例如'navigation',這允許jQuery變得高度選擇性。
$('#navigation a').click(
function() {
$('.current','#navigation').removeClass('current');
$(this).addClass('current');
return false;
}
);
這也部分解決了@Alec在評論中提出的問題,因為id
提供了一個獨特的上下文,可以在其中搜索.current
元素,防止影響散布在頁面周圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.