0

我有一些控制我的asp:LinkBut​​ton超链接的 CSS,我想了解如何在加载 MasterPage 时为当前页面设置WebControl 的 CssClass属性。

MasterPage上的这些asp:LinkBut​​ton超链接包含在一个列表中:

<ul id="menu">
  <li class="sprite">
    <asp:LinkButton ID="linkButton1" runat="server" PostBackUrl="~/linkButton1.aspx">
      <span>link 1</span>
    </asp:LinkButton>
  </li>
  <li class="sprite">
    <asp:LinkButton ID="linkButton2" runat="server" PostBackUrl="~/linkButton2.aspx">
      <span>link 2</span>
    </asp:LinkButton>
  </li>
  <li class="sprite">
    <asp:LinkButton ID="linkButton3" runat="server" PostBackUrl="~/linkButton3.aspx">
      <span>link 3</span>
    </asp:LinkButton>
  </li>
</ul>

MasterPage中,我尝试使用 Page_Load 事件设置 CssClass:

protected void Page_Load(object sender, EventArgs e) {
  if (!IsPostBack) {
    linkButton1.CssClass = "";
    linkButton2.CssClass = "";
    linkButton3.CssClass = "";
    string linkButtonID = Request.RawUrl;
    if (-1 < linkButtonID.IndexOf("linkButton2")) {
      linkButton2.CssClass = "active";
    } else if (-1 < linkButtonID.IndexOf("linkButton3")) {
      linkButton3.CssClass = "active";
    } else {
      linkButton1.CssClass = "active"; // default
    }
  }
}

MyCssClass="active"似乎从未设置过,并且查看页面源代码可以快速验证我的所有 LinkBut​​ton 控件都没有设置 CssClass 属性。

由于这很难想象,我整理了一个 jsFiddle。该站点不支持 ASP,但它可以帮助您想象我想要完成的任务:

http://jsfiddle.net/jp2code/kZQwC/

如何让我的活动页面设置 CssClass?

4

1 回答 1

1

您正在分配班级,!IsPostBack恐怕您当时的网址没有linkBut​​ton1、linkBut​​ton2 或linkBut​​ton3。

您接受class assignment code out of the if condition并检查您是否执行了这些条件并获得了课程。

改变

if (!IsPostBack) {
    linkButton1.CssClass = "";
    linkButton2.CssClass = "";
    linkButton3.CssClass = "";
    string linkButtonID = Request.RawUrl;
    if (-1 < linkButtonID.IndexOf("linkButton2")) {
      linkButton2.CssClass = "active";
    } else if (-1 < linkButtonID.IndexOf("linkButton3")) {
      linkButton3.CssClass = "active";
    } else {
      linkButton1.CssClass = "active"; // default
    }
}

linkButton1.CssClass = "";
linkButton2.CssClass = "";
linkButton3.CssClass = "";
string linkButtonID = Request.RawUrl;
if (-1 < linkButtonID.IndexOf("linkButton2")) {
  linkButton2.CssClass = "active";
} else if (-1 < linkButtonID.IndexOf("linkButton3")) {
  linkButton3.CssClass = "active";
} else {
  linkButton1.CssClass = "active"; // default
}
于 2012-08-10T17:56:05.283 回答