代码之家  ›  专栏  ›  技术社区  ›  BioXhazard

找不到asp:textbox in Javascript语言

  •  3
  • BioXhazard  · 技术社区  · 16 年前

    我正在尝试将onkeydown属性添加到asp:textbox. 由于某些原因,我的代码找不到loginview中的文本框。

    我做错什么了吗?

    <script type="text/javascript">
    window.onload = function() {
        UserName.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
        Password.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
    }
    
    function KeyDownHandler(btn)
    {
        if (event.keyCode == 13)
        {
            event.returnValue=false;    
            event.cancel = true;
            document.getElementById(btn).click();
        }
    }
    </script>
    
    3 回复  |  直到 16 年前
        1
  •  1
  •   David    16 年前

    您的代码正在尝试在客户端脚本中添加事件处理程序属性。这需要在服务器端代码块中发生。比如:

    <script runat="server"> 
        UserName.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')"); 
        Password.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')"); 
    </script>
    <script type="text/javascript">
    function KeyDownHandler(btn) 
    { 
        if (event.keyCode == 13) 
        { 
            event.returnValue=false;     
            event.cancel = true; 
            document.getElementById(btn).click(); 
        } 
    } 
    </script> 
    

        2
  •  0
  •   Humberto    16 年前

    在aspx文件中,添加将现有用户名和密码文本框绑定到名为KeyDownHandler的客户端事件处理程序的服务器脚本:

    <script runat="server">
       protected void Page_Load(object sender, EventArgs e)
       {
          TextBox userNameControl = FindControl("UserName") as TextBox;
          TextBox passwordControl = FindControl("Password") as TextBox;
    
          if (userNameControl != null)
             userNameControl.Attributes.Add("onKeyDown", "KeyDownHandler(this)"); 
    
          if (passwordControl != null)
             passwordControl.Attributes.Add("onKeyDown", "KeyDownHandler(this)"); 
       }
    </script>
    

    然后声明事件处理程序的客户端脚本:

    <script type="text/javascript">
    function KeyDownHandler(domButton) 
    { 
        if (event.keyCode == 13) 
        { 
            event.returnValue=false;     
            event.cancel = true; 
            domButton.click(); 
        } 
    } 
    </script>
    
        3
  •  -1
  •   Humberto    16 年前

    尝试按以下方式连接事件处理程序参数:

    <script type="text/javascript">
        window.onload = function() {
        UserName.Attributes.Add("onKeyDown", "KeyDownHandler(this)");
        Password.Attributes.Add("onKeyDown", "KeyDownHandler(this)");
    }
    
    function KeyDownHandler(domButton)
    {
        if (event.keyCode == 13)
        {
            event.returnValue=false;    
            event.cancel = true;
            domButton.click();
        }
    }
    </script>