你如何调用从ASPX控制事件的Javascript功能? [英] How do you call a Javascript function from an ASPX control event?

查看:108
本文介绍了你如何调用从ASPX控制事件的Javascript功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从一个ASPX控件事件调用JavaScript函数?

How do you call a Javascript function from an ASPX control event?

具体来说,我想从一个DropDownList的SelectedIndexChanged事件调用该函数。

Specifically, I want to call the function from the SelectedIndexChanged event of a DropDownList.

推荐答案

我变得有点紧张,每当我看到这样的问题,因为十之八九它意味着提问者并没有真正明白发生了什么事情。

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.

在服务器上的SelectedIndexChanged事件触发,它触发一个的完全回发的一部分。这意味着,为code运行,您的网页加载code的整个休息也有运行。

When your SelectedIndexChanged event fires on the server, it fires as part of a full postback. That means that for that code to run, the entire rest of your page's load code also had to run.

不仅如此,在code运行作为来自浏览器的新的http请求的结果。至于浏览器而言,一个全新的页面是回来的结果。旧的页面,而旧的DOM,将被丢弃。因此,在您的SelectedIndexChanged事件code运行的时候,你要调用甚至没有在浏览器中存在的JavaScript函数。

More than that, the code runs as the result of a new http request from the browser. 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. So at the time your SelectedIndexChanged event code is running, the javascript function you want to call doesn't even exist in the browser.

那么怎么办呢?您有几种选择:

So what to do instead? You have a few options:


  • 更改页面,以便该控件不回发到服务器的。完全在客户端检测在JavaScript的变化。这是我的preferred选项,因为它避免了在浏览器页面的onload奇脚本和为您的服务器保存的工作。不利的一面是,它使你的页面依赖于JavaScript,但是这不是一个真正的大问题,因为如果禁用JavaScript这是从一开始就注定要失败。

  • 设置所需的javascript中使用ClientScript.SetStartupScript()SelectedIndexChanged事件的onload运行。

  • 申请您的JavaScript的预期结果页面的服务器模式。这有即使JavaScript是关闭(无障碍)工作的优势,但在做更多的工作在服务器上,花费更多的时间推理你的页面的逻辑状态,并可能需要重复客户端的成本,服务器端逻辑。此外,这一事件依赖于JavaScript的反正:如果JavaScript被禁用,它会不火

  • 的第一和第三个选项的一些组合也是可能的,使得它使用JavaScript本地如果可用,但回发到服务器如果不。我个人希望看到更好,更直观,对于内置ASP.Net支持。但同样:我说的是一般情况。此特定事件需要JavaScript才能在所有工作。

这篇关于你如何调用从ASPX控制事件的Javascript功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆