我必须调用两个 js 函数,将焦点设置在文本框上,并停止在单击按钮时发生回发。如果我只能拦截回发,我想我就明白了。我的 js 技能与 weaksauce 不相上下。
测试用例
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsTextFocus.aspx.cs" Inherits="WebApplication1.JsTextFocus" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="Javascript">
function aMethod() {
var dowork = 'bleh';
}
function setFocusOnTextBox() {
TextBox1.Focus();
return false;//Stop the postback..FAIL
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="imageBtn" runat="server" ImageUrl="images/document_Small.gif" CausesValidation="false" OnClientClick="aMethod();return setFocusOnTextBox();return false;" />
</div>
</form>
</body>
</html>
页面加载不应在 OnClientClick 之后触发
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("PS happened at " + DateTime.Now);
}
最佳答案
您指的是 setFoucs.. 函数中的 TextBox1,此时未知。使用 document.getElementByID 获取对文本框的引用,然后调用 focus 而不是 Focus。
function setFocusOnTextBox()
{
var TextBox1 = document.getElementById("TextBox1");
TextBox1.focus();
return false;
}
您可以删除 Image ClientClick 处理程序末尾的 return false。 即:
<asp:ImageButton ID="imageBtn"
runat="server"
ImageUrl="images/document_Small.gif"
CausesValidation="false"
OnClientClick="aMethod();return setFocusOnTextBox();" />
关于javascript - 让我摆脱 JavaScript 回发故障船,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4787363/