[英]How do you call a Javascript function from an ASPX control event?
How do you call a Javascript function from an ASPX control event?如何从 ASPX 控制事件中调用 Javascript function?
Specifically, I want to call the function from the SelectedIndexChanged event of a DropDownList.具体来说,我想从 DropDownList 的 SelectedIndexChanged 事件中调用 function。
I get a little nervous whenever I see this kind of question, because nine times out of ten it means the asker doesn't really understand what's going on.每次看到这种问题我都会有点紧张,因为十有八九这意味着提问者并不真正理解发生了什么。
When your SelectedIndexChanged event fires on the server, it fires as part of a full postback .当您的 SelectedIndexChanged 事件在服务器上触发时,它会作为完整回发的一部分触发。 That means that for that code to run, the entire rest of your page's load code also had to run.
这意味着要运行该代码,您的页面加载代码的整个 rest 也必须运行。
More than that, the code runs as the result of a new http request from the browser.不仅如此,该代码作为来自浏览器的新 http 请求的结果运行。 As far as the browser is concerned, an entirely new page is coming back in the result.
就浏览器而言,结果中将返回一个全新的页面。 The old page, and the old DOM, are discarded.
旧页面和旧 DOM 被丢弃。 So at the time your SelectedIndexChanged event code is running, the javascript function you want to call doesn't even exist in the browser.
因此,在您的 SelectedIndexChanged 事件代码运行时,您想要调用的 javascript function 甚至不存在于浏览器中。
So what to do instead?那么该怎么做呢? You have a few options:
你有几个选择:
As Muerte said you have to just put the javascript, or a call to it on the page from the code behind.正如 Muerte 所说,您只需将 javascript 或从后面的代码调用到页面上即可。 Personally I use this:
我个人使用这个:
ClientScript.RegisterClientScriptBlock("customscript", "<script>simple script here</script>")
Of you can call the function if you already have a more complex one on the page instead of the stuff I have.如果您在页面上已经有一个更复杂的而不是我拥有的东西,您可以调用 function。
You can't do it directly from an event, because ASPX control event is server side.您不能直接从事件中执行此操作,因为 ASPX 控件事件是服务器端的。
What you can do is emit a Javascript in the ASPX event which will call the JavaScript function when the page reloads.您可以做的是在 ASPX 事件中发出 Javascript,该事件将在页面重新加载时调用 JavaScript function。
For example, if in your ASPX page you have a Javascript function called "DoSomething()", in you ASPX control event, add the following:例如,如果在您的 ASPX 页面中有一个名为“DoSomething()”的 Javascript function,则在您的 ASPX 控件事件中添加以下内容:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myEvent", "DoSomething()", true);
}
The last boolean parameter defines that tags are added automatically.最后一个 boolean 参数定义自动添加标签。
In the code behind, attach some markup to the server side control via its attributes collection.在后面的代码中,通过属性集合将一些标记附加到服务器端控件。 This assumes that the function is already in a client script file that is already available to the page.
这假设 function 已经在页面可用的客户端脚本文件中。
MyServerDDLControl.Attributes.Add("SelectedIndexChanged", "MyClientSideFunction();");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.