I have a dynamically created UL. I want to use jQuery to use the current URL, search through a specified UL and find any li with a matching href. If one is found then add the class "current_page".
I came up with this but it doesn't seem to do the trick.
$(document).ready(function() {
$("ul.nav_cat_archi开发者_StackOverflow中文版veli").find("a[href='"+window.location.pathname+"']").each(function() {
$(this).addClass("current_page");
});
});
You can play with window.location which will return the current page URL and also the href property of the window.location
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var windowLocationPathname = "/HTMLPage16.htm"; // For testing purpose.
//Or
//var windowLocationPathname = window.location.pathname;
$('ul.nav_cat_archiveli').find('a[href^="' + windowLocationPathname + '"]').addClass('currentPage');
});
</script>
<style type="text/css">
.nav_cat_archiveli
{
list-style: none;
}
a.currentPage
{
color: Red;
background-color: Yellow;
}
</style>
</head>
<body>
<ul class="nav_cat_archiveli">
<li><a href="/HTMLPage14.htm">Test 1 (/HTMLPage14.htm)</a></li>
<li><a href="/HTMLPage15.htm">Test 2 (/HTMLPage15.htm)</a></li>
<li><a href="/HTMLPage16.htm">Test 3 (/HTMLPage16.htm)</a></li>
<li><a href="/HTMLPage17.htm">Test 4 (/HTMLPage17.htm)</a></li>
</ul>
</body>
</html>
精彩评论