由于之前的网站大部分已经完成.现在要增加在搜索框中输入关键字后按回车直接提交.先写个demo测试一下.可以完成.
在IE的文本框里面按回车..默认是表单提交
判断在按回车时返回掉就OK 不会提交了
友情提示:FF下面JS代码失效.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public int i
{
get
{
int tmp = 0;
if (ViewState["i"]!=null)
{
int.TryParse(ViewState["i"].ToString(),out tmp);
}
return tmp;
}
set
{
ViewState["i"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write( i++);
}
protected void lkBtnSearch_Click(object sender, EventArgs e)
{
Response.Write(tbWords.Text);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tbWords" runat="server"></asp:TextBox>
<asp:LinkButton ID="lkBtnSearch" runat="server" onclick="lkBtnSearch_Click">LinkButton</asp:LinkButton>
</div>
</form>
</body>
</html>
function document.onkeydown()
{
if (event.keyCode ==13)
{
var e =event.srcElement;
//alert(e.nextSibling.id);//为什么用兄弟节点取不到?
//alert(e.parentElement.children[1].id);
if(e.tagName=='INPUT' && e.value.length>0)
{
var btn = e.parentElement.children[1];
if(btn && btn.tagName=='A')
{
btn.click();
return true;
}
}
return false;
}
}