我正在使用带有C#后端的ASP.NET站点。标签位于.Master页面,填写表单后,当您按Enter键时,网站上的其他搜索页面将会搜索。但是我们有一个页面有几个文本框,当你按Enter键进行搜索时,它似乎只是刷新并重新加载页面而不进行搜索。为了搜索,你必须点击搜索按钮(这是一个igtxt:WebImageButton)。到目前为止,我在这个问题上找到的所有解决方案都涉及到人们使用javascript在提交时调用某种功能。据我所知,当你点击搜索按钮时没有调用javascript,它全部都在C#代码中。我再次发现自己搜索SO和其他网站的答案,但没有一个解决方案似乎适合我的情况。表单标签如下:
<form id="form1" runat="server">
Web图像按钮调用运行搜索代码的btn_SearchClick函数。但是由于表单是在.Master文件中启动的,我无法编辑它,因为它也会影响所有其他页面。是否有任何方法可以从表单中调用btn_SearchClick而无需将其放在表单标记中?我不确定在一个页面上会导致这种行为的改变是什么,而不是其他任何一个。
答案 0 :(得分:1)
if (!IsPostBack)
{
TextBox1.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
}
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>
或者您可以使用默认button.it的工作,而光标在此框中
protected void Page_Load(object sender, EventArgs e)
{
this.Form.DefaultButton = this.btnSubmit.UniqueID;
}
答案 1 :(得分:0)
添加一些jquery来控制文本框中的Enter键行为。像这样:
$(function() {
$('#<%=txtTextbox.ClientID%>').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
$('#<%=btn_SearchClick.ClientID%>').click();
}
});
});