基于URL的活动链接

时间:2014-12-05 11:58:48

标签: jquery

任何人都可以帮助我..我想根据我的网址在我的菜单上添加一个活跃的课程

这是代码

<div class="taglist">
<a class="automotive" title="Automotive Tag" href="#">Automotive</a>
<a class="banca" title="Banca Tag" href="#">Banca</a>
<a class="banking-pt" title="Banking Tag" href="#">Banking</a>
<a class="big-data" title="Big Data Tag" href="#">Big Data</a>
<a class="bigdata" title="BigData Tag" href="#">BigData</a>
<a class="cloud" title="Cloud Tag" href="#">Cloud</a>
</div>

可能的网址

http://www.whatever.com/?tag=automotive,big-data,cloud
http://www.whatever.com/?tag=automotive,big-data
http://www.whatever.com/tag/automotive

所以,我需要的是当URL为http://www.whatever.com/?tag=automotive,big-data时,我想再添加一个类,比如活动。

示例:

URL: http://www.whatever.com/?tag=automotive,big-data

HTML:

<div class="taglist">
<a class="automotive active" title="Automotive Tag" href="#">Automotive</a>
<a class="banca" title="Banca Tag" href="#">Banca</a>
<a class="banking-pt" title="Banking Tag" href="#">Banking</a>
<a class="big-data active" title="Big Data Tag" href="#">Big Data</a>
<a class="bigdata" title="BigData Tag" href="#">BigData</a>
<a class="cloud" title="Cloud Tag" href="#">Cloud</a>
</div>

2 个答案:

答案 0 :(得分:1)

这种代码风格适合您

// var url=document.URL;
var url="http://www.whatever.com/tag/automotive/";

// remove latest /
if (url[url.length-1] == "/")
{url = url.substring(0, url.length-1);}
alert(url);

// when "tag/"
if(url.indexOf("tag/") != -1){
    url = url.split('tag/')[1];
}
// when "tag="
else
{
    url = url.split('tag=')[1];
}
// split in table
var tagArray = url.split(',');
// foreach table item put active on menu links
for (var i = 0; i < tagArray.length; i++) {
        $( "."+tagArray[i] ).addClass( "active" );    
}

您可以在此处查看工作代码:http://jsfiddle.net/mh7ory9n/8/

答案 1 :(得分:0)

我刚用@clement使用vanilla js做了类似的例子。例如,您可以使用tags.push(&#34; item3&#34;)更新标签数组。

//var url = "http://www.whatever.com/tag/automotive/big-data/";
var url = "http://www.whatever.com?tag=automotive,big-data";
getActiveItems(url);

function getActiveItems(url) {

    if (url.indexOf("tag=") == -1) {
        if (url[url.length-1] == "/")
            url = url.substring(0, url.length-1);
        var tags = (url.split("tag/"))[1].split("/");
    } else {
        var tags = (url.split("tag="))[1].split(",");
    }

    var listElements = document.getElementById("navbar").getElementsByTagName("li");
    for (i = 0; i < listElements.length; i++) {
        tags.map(function (elem) {
            if ((listElements[i].className).indexOf(elem) != -1) 
                listElements[i].className += ' active'
        });
    }
}

您可以在该链接上看到正在运行的示例:http://jsfiddle.net/newpatriks/xes9tvpa/