jquery needs to rebind events on partial page post

2019-02-13 15:47发布

How can I rebind my events (jquery) when I perform a partial page postback?

I am wiring everything up using:

$(document).ready(function(){};

After a partial page postback, my events are not firing.

5条回答
beautiful°
2楼-- · 2019-02-13 16:03

Check out the "live" feature of jQuery 1.3 here. You can add events to future elements as well as current elements on the page. This may simplify the code you'll need to write.

查看更多
Ridiculous、
3楼-- · 2019-02-13 16:08

The most elegant solution (using jQuery 2.x) is this:

Use the "on" event. Make sure you bind the event to the document and not to the element itself!

Code example:

$(document).on('click', 'div.messages', function () {
    console.log('click on div.messages');
    return false;
});

Put this code into document.ready for example.

This works even if div.messages is changed or created inside an UpdatePanel. And it is never fired twice or more times at once.

查看更多
forever°为你锁心
4楼-- · 2019-02-13 16:15

I'm guessing from 'partial page postback' you're working in Asp.net land.

Try using

Sys.Application.add_load(function() { });

You should still be able to use all the normal jQuery stuff inside that func.

查看更多
甜甜的少女心
5楼-- · 2019-02-13 16:15

Some DOM elements are replaced when you do a partial postback, and of course, the new elements will loose jQuery bindings. You can use the ScriptManager class to register a script that will be executed after the partial postback finishes (have a look here)

查看更多
女痞
6楼-- · 2019-02-13 16:27

You can either tap into the PageRequestManager endRequestEvent:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

Or if it is control events you're trying to attach, you can use jQuery live events.

Another option is to do the event delegation manually. It is what the "live" event are doing under the covers. Attach the event handler to the document itself, then conditionally execute your method if the sender of the event was element you expect.

$(document).click(function(e){  
    if($(e.target).is(".collapseButton")){  
        $(this).find(".collapsePanel").slideToggle(500);  
    }  
})  
查看更多
登录 后发表回答