Reputation: 967
i want to assign a class to an a href tag if this his clicked, in other words, if one address is in the address bar, assign one class to this tag..
I have this styles in my css..
ul#menu li a {
padding: 10px 20px;
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
color: #465c71;
}
ul#menu li a.selected {
padding: 10px 20px;
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
color: #FFFFFF;
}
Where only change the font color..
And this jquery script in the Layout page of my mvc3 project..
I have this function..
<script type="text/javascript">
$(function () {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$("#menu li a").each(function () {
var addr = $(this).attr("href").lastIndexOf("/") + 1;
if (addr == pgurl)
$(this).addClass("selected");
})
});
</script>
Where pgurl is the bold value http://local.host:81/Home/Services (Sure, because i use and works in another jquery function)
And I have a a href link like this..
<li><a href="@Url.Action("Services", "Home")">@MvcWebRole1.Resources.Shared.Layout.Services</a></li>
And this above generates a link as this..
<a href="/Home/Services">Services</a>
Where i want to add a class to this tag if the first variable is the same of page that i am.. I i do through firebug or similar (add manually the class) works as expected..
Finally, two variables should have the bold value(Services), but doesnt add the class at the tag, i work with Visual Studio 2010 and i cant test this values, i cant put any breakpoint on it to view their values.. And as commented above, i have another similar function thats works perfectly with the tags of another list..
Can someone help me?
Thanks.
Upvotes: 0
Views: 101
Reputation: 25445
var addr = $(this).attr("href").lastIndexOf("/") + 1;
The above assigns a number
+ 1 to addr
. You then go on to test this number is equal to a string so unless your action is a number (not sure if it can be), then it will always fail.
Maybe you meant to get the substring from the link as well
var addr = $(this).attr("href").substr($(this).attr("href").lastIndexOf("/") + 1);
Upvotes: 1