2012-04-24 63 views
0

我正在製作一個菜單,我想將class =「selected」添加到活動的菜單項中。我有location.pathname問題時,URL是這樣的: - http://www.google.com/sub-folder/adrov48.phpjQuery和活動菜單項 - 什麼是最好的?

所以basicaly只能當URL很簡單那樣: - http://www.google.com/adrov50.php

我知道有很多similair問題,但如果你拿看看下面我用一個「新」的方法,但它不是真正的工作代碼,這就是你們的:)

Javascript代碼跳:

  var path = location.pathname; 

      $("a[href='" + [path] + "']").parents("li").each(function() { 
        $(this).addClass("selected"); 
      }); 

任何想法如何使用jQuery進行此項工作。

如果有人認爲我的方法不好或不理想,請告訴我爲什麼併發布或鏈接我的解決方案。

在此先感謝!

回答

1

你爲什麼不這樣做:

// Check complete URL 
var path = location.href; 
$("#navID li a").each(function() { 
    // Check if there is a match between the URL and the navigation link  
    if(path.match($(this).attr("href")) $(this).parent().addClass("selected"); 
}); 
+0

因爲在我的hrefs我沒有完整的網址:S Basicaly => href =「http://www.google.com/sub-folder/adrov48.php」不能匹配href =「adrov48。 php「... – ProDraz 2012-04-24 14:19:44

+0

你實際上在這裏匹配」adrov48.php「到」google.com/sub-folder/adrov48.php「.. – kayen 2012-04-24 14:22:27

+0

它只是不工作,這是我測試過的代碼=> http://jsfiddle.net/umhdy/ – ProDraz 2012-04-24 14:26:35

1

結合location.pathname和location.search創建網址片段

+0

也許演示?謝謝! :) – ProDraz 2012-04-24 14:09:33