Running javascript function every MenuItem from Asp: Menu

I want to run a simple javascript function for each MenuItem from an asp: menu.

<asp:Menu ID="_mainMenu" runat="server" ClientIDMode="Static" EnableTheming="False" StaticBottomSeparatorImageUrl="~/Images/menuSeparator.gif" Orientation="Horizontal" RenderingMode="Table" OnMenuItemClick="_menu_MenuItemClick" SkipLinkText=""> </asp:Menu> 

If I add an attribute to the _mainMenu.Attributes.Add("onclick", "javascript:jsFunction();") , I get the onclick event only in the table, which describes the menu for not every MenuItem element, which are links to other pages.

+4
source share
1 answer

First add the css class to the menu:

 <asp:Menu ID="_mainMenu" runat="server" CssClass="MyMenu" ... 

Then you can use this jQuery code to handle the click event of all the links inside:

 <script type="text/javascript"> $(function() { $(".MyMenu a").each(function(index) { $(this).click(function() { alert($(this).attr("href")); return false; }); }); }); </script> 

In the above example, a warning with a href link will be displayed when clicked, you can do whatever you want. It will also cancel the link, just delete "return false"; to redirect the link as usual.

+4
source

All Articles