问题
I'm trying to make jQuery menu, which can highlight current page. Method is, add class current
on selected.
Here is html:
<div class="menu_items">
<ul class="ul_items" id="navigation">
<li><a href="index.php">1</a></li>
<li><a href="index.php?pg=2">2</a></li>
<li><a href="index.php?pg=3">3</a></li>
<li><a href="index.php?pg=4">4</a></li>
<li><a href="index.php?pg=5">5</a></li>
</ul>
</div>
And I tried to make something like that:
$(document).ready(function(){
$("#navigation").find("a[href*='"+window.location.href+"']").each(function(){
$(this).addClass("current")
});
});
Because CSS code is large and etc, complete codes are at jsFiddle
I think that something isn't properly defined in Jquery part of code. When I try this:
var a = $("#navigation").find("a[href*='"+window.location.href+"']");
alert(a);
I get [Object] [Object] alert. Can someone help?
Thanks in advance.
回答1:
jQuery methods always return a jQuery object. If you want to see what's in it, try .length
to see how many elements were matched, and [0]
to access the individual DOM nodes. Or even better - console.log
it so you can inspect everything in it easily.
Your problem is though that location.href
returns the whole URL (http://...
) and your links don't contain that. You could use location.pathname
to get the path, but the real correct way to highlight the current page is to do it on the server side. No reason to use JS for something like this.
回答2:
Matti is true. But what you can try is the split() method to get the exact value to match the href.
working example: http://jsfiddle.net/ylokesh/AqmHr/2/
<script>
$(document).ready(function() {
//capture URL
//var tempURL = window.location.href;
var tempURL = "http://www.websiteurl.com/index.php?pg=2"
var urlMatch = tempURL.split('.com')[1].split('/')[1];
var hrefVal = $("#navigation a:eq(1)").attr('href');
$("#navigation").find("a[href='"+hrefVal+"']").html('Current Page');
});
</script>
回答3:
//var url = 'file://one/two/three/index.php?pg=2'; // use this if testing on desktop
var url = window.location.href;
var filepath = url.lastIndexOf("/") + 1;
var matchThis = url.substr(filepath);
$('#navigation').find("a[href*='"+matchThis+"']").addClass('current');
No need for .each
credit - https://stackoverflow.com/a/1302339/3377049
来源:https://stackoverflow.com/questions/9150344/jquery-current-page-via-find-and-each-function