2013-09-24 20 views
-1

我正在嘗試編寫一個匹配腳本來檢測您的頁面..以及在同一頁面上的粗體鏈接指向您當前的頁面。如果在鏈接和窗口中的URL匹配,然後添加一個類

$(document).ready(function() { 

    var url = window.location.href; 
    var match = $("a").attr("href"); 


    if(url == match) { 
     $(match).parent().addClass("tomato"); 
    } 


}); 
+1

什麼是你的問題? –

+0

它似乎沒有工作。 – Blynn

回答

2

你可以嘗試這樣的。

$('a[href~="'+url+'"]').addClass("tomato"); 

希望這會對你有所幫助。

2

嘗試

$('a').each(function() { 
    if ($(this).attr('href') == window.location.href) { 
     $(this).addClass('tomato'); 
    } 
}); 
0
$('a').each(function() { 
    var self = $(this); 

    if (self.attr("href") == url) { 
      // do something.. 
      self.css('font-weight', 'bold'); 
    } 
}); 

http://jsfiddle.net/qbdTR/

+0

這不起作用,當我這樣做.. http://jsfiddle.net/qbdTR/1/ – Blynn

+0

它的工作原理,它不是因爲你的地址不正確(jsfiddle與iframe一起工作)http://jsfiddle.net/qbdTR/2 /(點擊'運行')。 –

0

有在你的代碼簡單的錯誤。

var anchor = $(「a」);
var match = anchor.attr(「href」);
$(錨).parent().....

$(document).ready(function() { 
    var url = window.location.href; 
    var anchor = $("a"); 
    var match = anchor.attr("href"); 

    if(url == match) { 
     $(anchor).parent().addClass("tomato"); 
    } 
}); 

這將是更好,如果你可以使用;
1.擁有id或class的父母 - $(anchor).parent('#anchorParent') - 在HTML中也使用相同的id。
2.或使用$(anchor).parents('div:eq(0)')作爲第一個母公司。

同樣的事情適用於錨太HTML:<a id="myAnchor">,腳本:$("#myAnchor");

相關問題