admin管理员组

文章数量:1415467

I want to run an simple javascript function on 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 the attribute on Page_Init _mainMenu.Attributes.Add("onclick", "javascript:jsFunction();") I get onclick event only on a table that describes the menu not on each MenuItem that are links to other pages.

I want to run an simple javascript function on 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 the attribute on Page_Init _mainMenu.Attributes.Add("onclick", "javascript:jsFunction();") I get onclick event only on a table that describes the menu not on each MenuItem that are links to other pages.

Share Improve this question edited Mar 29, 2012 at 19:36 Pankaj 10.1k39 gold badges151 silver badges297 bronze badges asked Nov 24, 2010 at 10:01 MaPaMaPa 555 silver badges8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

First add 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 links inside:

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

The above example will show alert with the link href when it's clicked, you can do whatever you want instead. It will also cancel the link, just remove the "return false;" line to have the link redirect as usual.

本文标签: aspnetrunning javascript function each MenuItem from AspMenuStack Overflow