简体   繁体   中英

jQuery selectors not working after ASP.NET postback (no UpdatePanels, not AJAX)

I need to make a change to an old page as quickly as possible, and the effort to AJAX-ify it in order to obviate postbacks would take too long (making a more correct version of it will have to come later, this new functionality needs to be in place ASAP). The javscript changes required are too complicated to attempt entirely in the plain JS the page currently uses for everything (it's enough of a mess as is), so I decided to implement the new functionality quickly using jQuery.

Everything works fine until there's a postback, after which the document ready function still runs, but the selectors no longer find anything. I'm not using ASP.NET AJAX, so there's no UpdatePanels or partial postbacks.

What's happening and how can I fix it in the simplest, fastest possible way?

While $(document).ready() is ideal for one-time initialization routines, it leaves you hanging if you have code that needs to be re-run after every partial postback. Of course there are ways to get around this. But can you try using .NET franeworks pageLoad() and bind your events there and see if selectors still work after postback.

<script type="text/javascript">
  function pageLoad() {
    $("#Button1").on('click', function () {
       ...
    });
  }
</script>

If you have aa trigger attached to the DOM, and that element in the DOM gets replaced, the trigger will be lost. Such a trigger might look like $('#mydiv').on('click', function(){}); .

Instead, you have the attach the trigger to a DOM element that wont be replaced. The easy way is to attach this to the document , but you'd be recommended to narrow the search.

Such a selector would look like

$('document').on('click', '#mydiv', function() {});

This means that if the element #mydiv gets recreated, then the trigger is not lost.

You can read more about delegated events at http://api.jquery.com/on/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM