2010-12-10 69 views
0

全部標籤我想「活動」類添加到當前鏈接,我有以下代碼:jQuery的addclass當前的標籤,而不是裏面的div

jQuery的:

$("#products a").each(function() { 
if(this.href == window.location || this.href == document.location.protocol + "//" + window.location.hostname + window.location.pathname) 
$(this).addClass("selectedThumb"); 

});

的HTML:

<div id="products"> 
    <a>First product</a> 
    <a>Second product</a> 
</div> 

我想與點擊具有「selectedThumb」級只增加了流通環節結束了。眼下類被添加到所有的一個標籤,我結束了這一點:

<div id="products"> 
    <a class="selectedThumb">First product</a> 
    <a class="selectedThumb">Second product</a> 
</div> 

這是一個產品的形象拇指觀衆,所以我總是停留在當前頁面上,不會離開單擊鏈接之後的頁面,而是在頁面上更改產品縮略圖。該代碼工作正常。不知道這是否可以解決這個問題。

附加信息

的一個標籤,我試圖添加的「活躍」狀態/ CSS類是拇指的圖像,徘徊時,有顯示該頁面,拇指鼠標懸停事件,拇指沒有聯繫。

mouseover事件調用JS函數,顯示正確的產品圖像。

它調用JS:

function displayImage(index, parent){ 
var images = document.getElementById(parent).getElementsByTagName("div"); 

for(var i = 0; i < images.length; i++) { 
    var image = images[i]; 
    if (image.className != 'pimage') { continue } 
    if(i == index-1) { 
    image.style.display="block"; 
    } 
    else { 
    image.style.display="none"; 
    }  
} 

}

如此,是因爲一個鏈接真的不鏈接任何地方,jQuery的addClass被添加到所有縮略圖的鏈接。

回答

0

也許嘗試匹配的URL(未經測試):

var loc = window.location.href; 
$("#products a").each(function() { 
if (loc.match(this.href) { $(this).addClass("selectedThumb"); } 
}); 
+0

'loc.match(this.href)'不是一個好的比較器。 ''「http://example.com/some/deep/link".match("http://example.com」)== true' – nickf 2010-12-10 17:07:09

+0

是的,我假設他使用相對路徑=/ – Mottie 2010-12-11 04:59:07

1

我會試着在你的代碼,你現在要做什麼更加清晰。如果你想一類只適用於某一特定鏈接,然後只選擇鏈接:

$('#products a[href="' + window.location.href + '") 
    .addClass('selectedThumb') 
; 

如果這是你的東西特別需要經常選擇,這可能是整齊延長jQuery的:

$.extend($.expr[':'], { 
    currentPage: function(el) { 
     return el.href && el.href === window.location.href; 
    } 
}); 

// then... 
$('a:currentPage').addClass('selectedThumb'); 
+0

哇,謝謝爲快速反應!我在代碼中添加了一些更多細節,希望有所幫助。 @尼克,我嘗試了你的例子,但由於某種原因,仍然不工作。 – IntricatePixels 2010-12-10 18:07:09