[英]Change link to active onclick
對於網站中的所有頁面,我都有一個通用的標題。
當我單擊任何鏈接時,它將帶我到該頁面,並且頁面會刷新。
但是標題與上一頁相同。
我想要的是,當我單擊任何鏈接時,該鏈接將變為粗體(有效),並且如果我在主頁上,則默認情況下,主頁鏈接應處於活動狀態。
我正在嘗試解決此問題,當我單擊任何鏈接時,該鏈接變為活動(粗體),但是當頁面刷新並帶我到新頁面時,該鏈接變為非活動(正常)。
這是我的代碼。
<script type='text/javascript'>
$(window).load(function(){
$("#main-menu a").click(function() {
$('a').removeClass('active');
$(this).addClass("active");
});
});>
</script>
<style>
.active {font-weight:bold}
</style>
<!--Navigation-->
<nav id="main-menu">
<ul class="right">
<li><a href="#">Home</a></li>
<li><a href="#">Test Link 1</a></li>
<li><a href="#">Test Link 2</a></li>
<li><a href="#">Test Link 3</a></li>
</ul>
</nav>
有什么辦法可以使用通用標頭呢? 謝謝,
您想要做的是通過導航在兩個頁面之間傳遞值(狀態)。 將.active
應用於當前頁面的最佳方法是檢查您所在的頁面,然后通過jquery應用類
如果您的網站頁面為www.my.example.com/page1
則window.location.pathname
允許在域示例之后添加路徑,然后提供path1
注意諸如www.my.example.com/category/page1
之類的復雜情況,然后給出category/path1
這樣的代碼將起作用。 另請參閱此處的小提琴鏈接http://jsfiddle.net/52Aqu/10/
$(window).load(function(){
var checkvalue= window.location.pathname;
//alert(checkvalue);
$("a").each(function(){
if($(this).attr('href')== checkvalue)
{ $(this).addClass("active");}
});
});
對於您這種情況,當您實際上要對照url中的查詢參數和href中的查詢參數進行檢查時,請嘗試以下代碼:
$(window).load(function(){
var checkvalue= window.location.search;
//alert(checkvalue);
$("a").each(function(){
var hrefvalue="?" + $(this).attr('href').split("?")[1];
//alert(hrefvalue)
if(hrefvalue== checkvalue) { $(this).addClass("active");}
});
});
這里location.search
屬性提供來自URL的查詢參數。 如果頁面網址為www.example.com/sites/statics/static_page.html?name=global/canada/index
的示例, location.search
值將為?name=global/canada/index
然后對照href中的分割值檢查
您可以檢查例如window.location.pathname
並將其與導航的href進行比較。 含義:
var pathName = window.location.pathname;
$('nav a').each(function() {
var $self = $(this);
if($self.attr('href') ==pathName){
$self.addClass('active');
}
})
這樣的事情。
你不應該刪除類active
的a
,但.active
。 基本上,這會清除所有.active
類,以便您可以將其設置為當前單擊的鏈接。
腳本看起來像:
<script type='text/javascript'>
$(window).load(function(){
$("#main-menu a").click(function() {
$('.active').removeClass('active');
$(this).addClass("active");
});
});>
</script>
<style>
.active {font-weight:bold}
</style>
<!--Navigation-->
<nav id="main-menu">
<ul class="right">
<li><a href="#">Home</a></li>
<li><a href="#">Test Link 1</a></li>
<li><a href="#">Test Link 2</a></li>
<li><a href="#">Test Link 3</a></li>
</ul>
</nav>
我認為這段代碼可以為您提供幫助。
var url = document.location.href; // Getting the url
var str = url.substr(0, url.lastIndexOf('/')); // get the specific url
var nUrl = url.substr(url.lastIndexOf('/')+1); // Get the page name from url
$('#menu li a').each(function(){
if( $(this).attr('href') === nUrl){ // Comparing if we on the same page or not
$(this).addClass('active'); // applying the class on the active page
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.