最近在做Jquery的一些东西,但是遇到一个无奈问题,整了很久,没有头绪,FF调试~查看~对比~,最后怀疑是UpdatePanle的问题,因为我发现我写的document.ready已经没有用了。
最后在网上找到一个解决方法。原来UpdatePanel执行后,不会执行document.ready方法。你必须再次在
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// 这里重新绑定你的事件
});
以下是原文
I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in $(document).ready
. For example:
$(function() { $('div._Foo').bind("mouseover", function(e) { // Do something exciting }); });
Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel.
What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of $(document).ready
?
回答:
An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.
What I've done to work around this is re-subscribe to the events I need after every update. I use $(document).ready()
for the initial load, then this snippet below to re-subscribe every update.
var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(function() { // re-bind your jquery events here });
The PageRequestManager
is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.
If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs)
so you can see what raised the event and only re-bind if needed.
Read more about the RequestManager here: asp.net/.../UpdatePanelClientScripting.aspx (If using .NET 2.0)
Here is the latest version of the documentation from Microsoft: msdn.microsoft.com/.../bb383810.aspx
One other option you may have, depending on your needs is to use jQuery's live()
event subscriber, or the jQuery plugin livequery
. These methods are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use live()
, so in those cases, you're better off re-subscribing.