我有一些CSS控制我的asp:LinkButton超链接,我想知道如何在MasterPage加载时为当前页面设置WebControl's CssClass属性。
asp:LinkButton上的这些MasterPage超链接包含在列表中:
<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
}
}
}
我的CssClass="active"
似乎没有被设置,并且快速查看页面源会验证我的LinkButton控件都没有设置CssClass属性。
由于这很难想象,我把jsFiddle放在了一起。该网站不支持ASP,但它可以帮助您想象我想要实现的目标:
http://jsfiddle.net/jp2code/kZQwC/
如何让我的Active Page设置CssClass?
答案 0 :(得分:1)
您在!IsPostBack
中分配了课程我担心您当时的网址没有linkButton1,linkButton2或linkButton3。
你取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
}