Javascript 如何使 ASP.NET 中的代码隐藏中发生 onchange 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14201727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:00:22  来源:igfitidea点击:

how to make onchange event happened in code-behind in ASP.NET?

javascriptasp.net

提问by KentZhou

Suppose I have a textbox Mytbx and I have a javascript for its onchange event. I hook it up in code behind in Page_Load event like:

假设我有一个文本框 Mytbx 并且我有一个用于 onchange 事件的 javascript。我将它连接到 Page_Load 事件后面的代码中,例如:

Mytbx.Attributes.Add("onchange", "test();")

Then I changed the text in code-behind for this textbox like (in a button click event for example):

然后我更改了此文本框的代码隐藏中的文本(例如,在按钮单击事件中):

Mytbx.Text = MyValue

I expect onchange event fired. but actually, it's not. When I click on the button to change value for Mytbx, nothing happening.

我希望 onchange 事件被触发。但实际上,并非如此。当我单击按钮更改 Mytbx 的值时,什么也没有发生。

How to resolve this problem?

如何解决这个问题?

回答by phnkha

onchange will only be triggered on client side when you directly type something and leave the textbox. So nothing will happen when you set the textbox value in code behind.

只有当您直接输入内容并离开文本框时,才会在客户端触发 onchange。因此,当您在后面的代码中设置文本框值时,什么也不会发生。

If you want to handle the text change event on client side:

如果要在客户端处理文本更改事件:

<script>  
     function test(txt){
         alert(txt.value);
     };
</script>

<asp:TextBox ID="txt" runat="server" onchange="test(this);"></asp:TextBox>

If you want to handle text change event on server side, you could do this:

如果你想在服务器端处理文本更改事件,你可以这样做:

HTML:

HTML:

<asp:TextBox ID="txt" runat="server" OnTextChanged="txt_OnTextChanged" AutoPostBack="true"></asp:TextBox>

CS:

CS:

protected void txt_OnTextChanged(object sender, EventArgs e)
{
     // Do something
}

回答by n8wrl

You are mixing client and server processing. If you change the textbox on the SERVER, there is no client code to run yet becuase you haven't posted the form back. If you have javascript code that has to run when you change something on the server, you need to register that Javascript function to run when the page loads when your postback is complete. Check this out: http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript(v=vs.110).aspx

您正在混合客户端和服务器处理。如果您更改了 SERVER 上的文本框,则还没有要运行的客户端代码,因为您还没有回发表单。如果您有在服务器上更改某些内容时必须运行的 javascript 代码,则需要注册该 Javascript 函数,以便在回发完成后页面加载时运行。看看这个:http: //msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript(v=vs.110).aspx