-1

I have few anchor tags inside a div and I need to retrieve the href values of all anchor tags. For example

<div id="sample">
<ul>
<li><a href="/location1">Location1</a></li>
<li><a href="/location2">Location2</a></li>
<li><a href="/location3">Location3</a></li>
<li><a href="/location4">Location4</a></li>
</ul>
</div>

Assuming I am in /location1, the li that has a href="/location1" should have a separate background color, say for example red. If I am in /location2 the corresponding li should have the same red color.

I am trying to retrieve the page url first and then store it in a variable.

var pageurl = (window.location.pathname);

But not too sure on how to retrieve the href and then map it based on the page urls.

4

3 回答 3

2

你做这样的事情:

// Get the active link first
var $links = $('#sample a').filter(function() {
    return this.href && this.href == location.pathname;
});

// Highlight the current li having the link
$links.closest('li').addClass('active');

在活动类中设置您想要应用的任何样式。

于 2013-06-12T13:31:06.020 回答
0

这是 jQuery 代码,需要添加 jQuery 库才能工作。它适用于页面加载

jQuery(document).ready(function(){
    var url=document.URL.split('?')[1];
    if(url == undefined){
        url = '';
    }
    if(url != ''){
        url = '#'+url;
        jQuery(url).trigger('click');
    }
    var url=document.URL.split('?')[1];
    if(url == undefined){
        url = '';
    }
    if(url != ''){                      
        // do here what you want to do
    }
    }
);
于 2013-06-12T13:34:02.190 回答
0
$(document).ready(function(){
    $('#sample ul li a').each(function(e){
        var href = $(this).attr('href');
        // do something with href
    });

});

于 2013-06-12T13:37:03.830 回答