ASP.NET OnTextChanged 事件未立即响应

ASP.NET OnTextChanged Event Not Responding Instantly

本文关键字:响应 事件 NET OnTextChanged ASP      更新时间:2023-09-26

它正在工作,但它没有立即响应。当我单击某处时,它正在工作。

我还尝试了onkeyPress技术:

<asp:TextBox ID="txtWriter" runat="server" onkeyPress="txtOnKeyPress"  ></asp:TextBox>

但是我收到一条消息,例如:

属性 'onkeyPress' 不是元素 'TextBox' 的有效属性。

哪个

版本的 ASP.NET?以下内容当然对我有用*

<script>
    function txtOnKeyPress() {
        console.log("txtOnKeyPress");
    }
</script>
<asp:TextBox ID="txtWriter" runat="server" onkeypress="txtOnKeyPress()" />

*虽然,我确实在函数名称中添加了()

无论如何,如果 ASP.NET 该属性名称有问题,您只需在客户端附加处理程序即可。根据您的需要,input事件可能更有意义。这是一种实时change事件,在编辑输入值(通过击键、剪切、粘贴等)时触发。下面是一个示例:

document.querySelector("input").addEventListener("input", function(e) {
  console.log("value: %o", this.value);
});
<input autofocus placeholder="type here"></input>

请注意此处的浏览器兼容性。

现在,前面的示例会随着对输入值的每次更改而触发...这可能是相当位的,即:简单键入"测试"的 4 次。由于您(大概)希望它触发服务器端代码,因此我们希望在实际发布表单之前等待快速连续进行的任何更改:

function __doPostBack(name, argument) {
  // dummy version of ASP.NET's __doPostBack  
  console.log("value: %o", document.getElementsByName(name)[0].value);
}
var t; // handle for our timeout
document.querySelector("input").addEventListener("input", function(e) {
  // input received... cancel the previous timeout, if any
  clearTimeout(t);
  // wait 1000 milliseconds (1 second) for more input before posting
  t = setTimeout(__doPostBack, 1000, this.name);
});
<input autofocus placeholder="type here" name="test-input"></input>

另请参阅:window.setTimeout()document.querySelector()document.getElementsByNameEventTarget.addEventListener()

在代码隐藏中:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack && Request.Form["__EVENTTARGET"] == txtWriter.UniqueID) {
        GridView1.DataSource = /* some data source */;
        GridView1.DataBind();
    }
}