Tho*_*ock 13 javascript asp.net-mvc
我的主页中有以下菜单:
<ul id="menu" class="lavaLampBottomStyle">
<li>
<%= Html.ActionLink("Employees", "Index", "Employees")%></li>
<li>
<%= Html.ActionLink("Customer", "Details", "Account")%></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我需要一种方法将当前活动li的css类设置为"current".
我的第一个猜测是在javascript的帮助下做到这一点.
我会在主页中包含这样的内容:
$("#menu li a").each(){
if($(this).attr("href") == '<%= *GET CURRENT PAGE* %>'){
$(this).parent("li").addClass("current");
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个好方法吗?
如果是,我如何获得当前的URL部分,如在href中?
如果不是,你的建议是什么?:-)
仅供参考,我之后生成的html:
<ul id="menu" class="lavaLampBottomStyle">
<li>
<a href="/KszEmployees/Index">Employees</a></li>
<li>
<a class="current" href="/">Customer</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
Joh*_*han 15
如果你想在服务器端做这一切,我之前就已经做过了.创建操作过滤器属性:
public class PageOptionsAttribute : ActionFilterAttribute
{
public string Title { get; set; }
public string Section { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller as ControllerBase;
if (controller != null)
{
controller.SetPageSection(this.Section);
controller.SetPageTitle(this.Title);
}
base.OnActionExecuting(filterContext);
}
}
Run Code Online (Sandbox Code Playgroud)
这会在我的ControllerBase类中调用我的所有控制器继承自的两个方法:
public class ControllerBase : Controller
{
public void SetPageSection(string section)
{
// use the section defined or the controller name if none
ViewData["PageSection"] = section != null ?
section : this.RouteData.Values["controller"].ToString();
}
public void SetPageTitle(string title)
{
ViewData["PageTitle"] = title;
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器方法上设置标题和页面部分:
public class HomeController : ControllerBase
{
[PageOptions(Title="Home Page", Section="Home")]
public ActionResult Index()
{ }
}
Run Code Online (Sandbox Code Playgroud)
然后我从我的母版页调用ViewData值(这不会干扰ViewData.Model):
<body class="<%=ViewData["PageSection"] %>">
Run Code Online (Sandbox Code Playgroud)
然后通过CSS引用,而不是调用.current,给每个导航项一个ID,然后使用body类结合该ID来确定当前页面.
body.home #HomeNav { /* selected */ }
body.about #AboutNav { /* selected */ }
Run Code Online (Sandbox Code Playgroud)
从window.location中提取当前位置.然后使用指定href属性值的选择器来选择那些匹配的元素(可能只有一个).
var currentLocation = window.location.href;
// probably needs to be massaged to extract just the path so that it works in dev/prod
$("#menu li a[href$="+currentLocation+"]").addClass("current");
Run Code Online (Sandbox Code Playgroud)
这可能是最不强化的方式.如果您可以指望用户启用了javascript,我认为这没有任何问题,并且有时我自己完成了.
Request.Url是您感兴趣的对象,用于获取服务器端的当前页面.tvanfosson使用window.location.href的建议也不错,如果你想把它完全留在客户端.
使用serverside的优点是,Request.Url具有易于访问的URL部分,例如Request.Url.Host等,以帮助满足链接修改需求.
| 归档时间: |
|
| 查看次数: |
15121 次 |
| 最近记录: |