javascript functions in .ascx
I've looked at about 5 Questions here on SOF and haven't really found a useful answer for this. How am I supposed to invoke my javascript functions from client-side events in my .ascx controls? Here is my .ascx file.. what most the answers have led me to:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UIMenu.ascx.cs" Inherits="controls_UIMenu" %>
<script language="javascript" type="text/javascript">
function insetItem(myMenu)
{
myMenu.setAttribute("class", "myClass");
}
</script>
<asp:Menu ID="Menu1" runat="server" Font-Bold="True" Font-Size="Large" Height="50px"
Orientation="Horizontal" Target="_self" StaticMenuItemStyle-HorizontalPadding="10px"
OnMenuItemClick="insetItem(this)" StaticMenuItemStyle-BorderStyle="outset">
<Items>
<asp:MenuItem NavigateUr开发者_JAVA技巧l="~/Home.aspx" Target="_self" Text="Home" Value="Home"></asp:MenuItem>
<asp:MenuItem NavigateUrl="~/Loaner.aspx" Target="_self" Text="New" Value="New"></asp:MenuItem>
</Items>
</asp:Menu>
I'm getting different errors when doing it this way. ".....ascx does not contain a definition for "insetItem"", and my other pages that use this file don't recognize it anymore. When I try to put the js on the actual .aspx pages that will be using it, I get the same no definition error.
I just started learning jscript, still pretty noob. I'm trying to make it so when the user down clicks a menu item, I want that item's borderstyle to change to "inset". I'm not sure how to change that attribute for the specific item that gets clicked either in javascript >_< but that's another question. If anyone could lead me the right way in doing this too, that'd be amazing. Thanks!The error comes from the "OnMenuItemClick" being an event handler on the server side. It's not finding an 'insetItem' on the server side, so is throwing the error.
If you want to have an action occur when the menu item is clicked, you might be able to put onclick="insetitem(this);return false;"
into the MenuItem
Tag
<asp:MenuItem onclick="insetitem(this);returnfalse;" NavigateUrl="~/Loaner.aspx" Target="_self" Text="New" Value="New"></asp:MenuItem>
The return false;
will prevent the page from doing a postback when the menu item is clicked.
I didn't set anything up to test this, it's all off the top of the head, so you may need to tweak it slightly to get it to work. :)
MenuItemClick
is acutally an MenuEventHandler
c# event handler. I believe you would be looking for some kind of OnClientClick
, or simply use the onclick
attribute.
Also I don't know if you are using any libraries, but jQuery
, Prototype
, or other make it very easy to bind this event listener unobtrusively when the document loads.
OnMenuItemClick is a server side event - not one ment to be caught on the client side with javascript.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.menuitemclick(v=vs.80).aspx
精彩评论