开发者

simple asp.net webforms ul li menu with selected class

I have a simple unordered list with links in it.

<body>
    <div id="topMenu">
        <ul>
            <li><a class="selected" href="../Default.aspx">Start</a></li>
            <li><a href="../Category/ShowAll.aspx">Categories</a></li>
            <li><a href="../Elements/ShowAll.aspx">Elements</a></li>
            <li><a href="../Articles/ShowAll.aspx">Articles</a></li>
        </ul>
    </div>
    <asp:ContentPlaceHolder ID="MainContentPlaceholder" runat="server">
    </asp:ContentPlaceHolder>
</body>

I want to change the class of the link i click to the "selected" class, which is the easiest way to do this. I thought about making it into linkbuttons and saving the info in the session, but that开发者_C百科 seems overkill, there has to be an easier approach?


Well, you can just put the <a> to be runat="server" and then access them from codebehind:

hyperLink.Attributes["class"] = "opened";

You can have this in your master page with the menu, and you can have your child pages send the id of the hyperlink they need selected, something like

In your master (the linkWrapper can be your <ul> as runat server):

(HyperLink)linkWrapper.FindControl(childPageMenuAnchorLinkId);

In your child:

masterPage.ChildPageMenuAnchorLinkId = "link_Customers";


If you are using jQuery, the link from this other SO question may help you out.

jQuery add class .active on menu

EDIT:
Corrected script to use the 'selected' class, not 'active' according to OP's use.

So, if I "borrow" the script from the other answer, I believe this will work, again, if you are using jQuery...

$(function(){
    var url = window.location.pathname, 
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
        // now grab every link from the navigation
        $('#topMenu ul li a').each(function(){
            // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass('selected');
            }
        });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜