There are four links with <a>
label in my webpage, I hope to redirect to new webpage and remove the underline of the link when I click a link.
The Code A can redirect new webpage when I click a link, but the underline of the link can’t be removed.
The Code B can remove the underline of the link when I click a link, but webpage can’t be redirected, how to fix it?
Code A
$(function () {
$(".mainMenu").click(function () {
$(".mainMenu").removeClass("mainMenuSelected").addClass("mainMenu");
$(this).addClass("mainMenuSelected");
});
});
<a id="id_home" href="/Default.aspx" class="mainMenu" >Home</a>
<a id="id_demo" href="/Demo.aspx" class="mainMenu">Demo</a>
<a id="id_help" href="/Help.aspx" class="mainMenu">Help</a>
<a id="id_about" href="/About.aspx" class="mainMenu">About</a>
.mainMenu {
font-size: 20px;
margin-right: 25px;
}
.mainMenuSelected {
text-decoration: none;
color: Blue;
}
Code B
$(function () {
$(".mainMenu").click(function () {
$(".mainMenu").removeClass("mainMenuSelected").addClass("mainMenu");
$(this).removeAttr("href").addClass("mainMenuSelected");
});
});
...//The same
Added Content:
The following Code C is my answer, it works well.
Code C
$(function () {
var filename = window.location.pathname.split('/').pop();
switch (filename.toUpperCase()) {
case "Default.aspx".toUpperCase():
setMainMenuSelected("#id_home");
break;
case "":
setMainMenuSelected("#id_home");
break;
case "Demo.aspx".toUpperCase():
setMainMenuSelected("#id_demo");
break;
case "Help.aspx".toUpperCase():
setMainMenuSelected("#id_help");
break;
case "About.aspx".toUpperCase():
setMainMenuSelected("#id_about");
break;
}
});
function setMainMenuSelected(id) {
$(id).removeAttr("href").addClass("mainMenuSelected");
}
2
Answers
I wouldn’t use Javascript to solve this. I’d do it right in the HTML code which creates your menu.
You can compare
HttpContext.Current.Request.Url.AbsolutePath
, which contains the path portion of the URL of the page you’re currently viewing, with thehref
of each menu item.I hope helps this solution. please check.