running javascript function each MenuItem from Asp:Menu
I want to run an simple javascript functio开发者_JS百科n 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.
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.
精彩评论