在TextBox中点击回车时 触发指定按钮click事件的解决方案

 我们可以在每个页面写上
<INPUT id="PassWord" runat="server" type="password" onkeydown="javascript:fnTrapKD('Login')">
类似的代码 ,然后嵌入或链接一段fnTrapKD函数的js代码完成这种效果 ,但这样应用的页面多了就会造成代码的混乱 , 因此有必要把他们封装起来. 在后台调用一个静态函数就可以达到效果,更加灵活.

步骤如下:
1.编写注册TextBox和Button的静态方法
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Cuyahoga.Web.UI
{
    
/// <summary>
    
/// Utility class that handles the ASP.NET default button issue.
    
/// Originally created by Janus Kamp Hansen - http://www.kamp-hansen.dk
    
/// Extended by Darrell Norton - http://dotnetjunkies.com/weblog/darrell.norton/ 
    
/// Tidied by Martijn Boland - http://www.cuyahoga-project.org
    
/// </summary>
    public class DefaultButton
    {
        
private DefaultButton()
        {
        }

        
/// <summary>
        
/// Sets the Button you want to submit when the Enter key is pressed within a TextBox.
        
/// </summary>
        
/// <param name="thisPage"></param>
        
/// <param name="textControl"></param>
        
/// <param name="defaultButton"></param>
        public static void SetDefault(Page thisPage, TextBox textControl, WebControl defaultButton)
        {
            textControl.Attributes.Add(
"onkeydown""fnTrapKD('" + defaultButton.ClientID + "', event)");
            
string scriptSrc = String.Format("<script type=\"text/javascript\" src=\"{0}\"></script>",
thisPage.ResolveUrl(
"~/js/DefaultButton.js"));
            thisPage.RegisterClientScriptBlock(
"DefaultButtonScript", scriptSrc);
        }
    }
}

2.编写js 函数 ,文件名DefaultButton.s 放在网站根目录的js文件夹下

// Sets default buttons.
//
 Originally created by Janus Kamp Hansen - http://www.kamp-hansen.dk
//
 Extended by Darrell Norton - http://dotnetjunkies.com/weblog/darrell.norton/ 
//
 Tidied by Martijn Boland - http://www.cuyahoga-project.org
function fnTrapKD(btnID, event)
{
    
var button = document.getElementById(btnID); // only recent browsers
    if (document.all) // IE
    {
        
if (event.keyCode == 13)
        {
            event.returnValue 
= false;
            event.cancel 
= true;
            button.click();
        }
    }
    
else if (document.getElementById)
    {
        
if (event.which == 13
        {
            event.returnValue 
= false;
            event.cancel 
= true;
            button.focus();
            button.click();
        }
    }
}

3.使用方法
在ascx.cs中使用:
 DefaultButton.SetDefault(this.Page, this.txtSearchQuery, this.btnSearch);//分别是当前页面 , TextBox, Button的引用

在aspx.cs中使用:
DefaultButton.SetDefault(thisthis.txtSearchQuery, this.btnSearch);

这样在TextBox中输入内容后 点击回车键 便能执行相应的Button事件.
代码来自Cuyahoga , 唉 看项目中高级点的代码还看不懂 只能做些简单技术的学习笔记...Created by jecray


posted @ 2007-08-29 00:41 jecray 阅读(1486) 评论(5) 编辑 收藏