0

I have a dynamically generated menu (C#), like this:

MenuItem(string text, string value, string imageUrl, string navigateUrl, string target)

MenuItem AdminLevel1 = new MenuItem("Admin", "Admin");
MenuItem AdminPedidosRegisto = new MenuItem("Questions", "AdminQ");

NavigationMenu.Items.Add(new MenuItem("Messages Received", "AdminMessagesR", "", "./Admin/Messages.ascx", "ContainerIframe"));

AdminPedidosRegisto.ChildItems.Add(new MenuItem("Pending", "AdminPending", "", "./Admin/Pedidos.ascx", "ContainerIframe"));`

Where ContainerIframe is the iframe's ID and NavigationMenu is the (asp:Menu)'s ID.

I want to set some JavaScript to be executed when I click a MenuItem.

Is there a way?

4

4 回答 4

1

尝试将以下代码放入 .aspx 页面的 head 标记中:

   <script type="text/javascript"> window.onload = function(){

    var menuTable = document.getElementById("<%=Menu1.ClientID%>");  //specify your menu id instead of Menu1 var menuLinks = menuTable.getElementsByTagName("a");
        for(i=0;i<menuLinks.length;i++)
        {
            menuLinks[i].onclick = function(){return confirm("u sure to postback?");}
        }
        setOnClickForNextLevelMenuItems(menuTable.nextSibling); } function setOnClickForNextLevelMenuItems(currentMenuItemsContainer){

        var id = currentMenuItemsContainer.id;
        var len = id.length;
        if(id != null && typeof(id) != "undefined" && id.substring(0,4) == "Menu" && id.substring(parseInt(len)-5,parseInt(len)) == "Items")
        {
            var subMenuLinks = currentMenuItemsContainer.getElementsByTagName("a");
            for(i=0;i<subMenuLinks.length;i++)
            {
                subMenuLinks[i].onclick = function(){return confirm("u sure to postback?");}
            }
            setOnClickForNextLevelMenuItems(currentMenuItemsContainer.nextSibling);
        } } </script>

请注意,您无需在代码隐藏文件中编写任何代码即可使此解决方案正常工作。我已经在 IE7 & FF2.0 中测试过代码

希望对你有效。

干杯!!

于 2012-12-13T12:55:55.417 回答
0

AdminLevel1.NavigateUrl = "javascript:callSomeFunction();";

于 2012-12-13T15:12:25.343 回答
0

感谢@Manibhadra(这对于父项和子项来说已经足够了)

window.onload = function ()
{
    var menuTable = document.getElementById("<%=NavigationMenu.ClientID%>");
    var menuLinks = menuTable.getElementsByTagName("a");
    for (i = 0; i < menuLinks.length; i++)
    {
        menuLinks[i].onclick = function () { setInnerHTML('ContainerTittle', this.innerHTML); }
    }
}
于 2012-12-14T10:46:16.387 回答
0

哈恩斯的回答似乎使所有项目都相同。

我使用以下内容:

  1. 使菜单项不可选择,因此它不会回发
  2. 在适当的地方添加以下代码:

Page.ClientScript.RegisterStartupScript(typeof(Page), "123", string.Format("$('#MenuDiv').find('a').filter(':contains(\"{0}\")').css('cursor', 'pointer').click(function(){{ {1} }});", Title, Script), true);

其中:
“123”是您的脚本的唯一键
MenuDiv 是您的菜单客户端 ID
Title 是您分配给菜单项的文本
Script 是您要运行的 javascript。

于 2014-03-19T21:03:41.637 回答