After postback my JavaScript function doesn't

2020-08-10 06:03发布

问题:

I have common functions and I collapse it on CommonFunctions.js in Scripts folder.

I include it on my master page and use it on my pages. When I do any post back on a page, my function doesn't work.

My CommonFunctions.js:

$(function () {

    gf();

   if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {

        gf();
    }


 function gf(){

    $('.AddNewGeneralPanel').click(function () {

        if ($(this).find('.AddNewGeneralPanelStyle').text() == "") {
            $(this).find('.AddNewGeneralPanelStyle').text("(  Gizle  )");
            lastOpenId = $(this).attr("kodid");
        }
        else
            $(this).find('.AddNewGeneralPanelStyle').text("");

        $(this).next('.AddNewGeneralAccordionDiv').slideToggle('slow', function () {

        });

    });
  }
});

回答1:

Since you're using an UpdatePanel, the part of the DOM that you've attached your event handler to is getting dropped and recreated after the postback. This has the effect of removing any event handlers that were attached by jQuery when the page first loaded.

When you postback only part of the page, the jQuery $(function() {}); doesn't fire again, so your handlers never get reattached.

Here's a related question that shows how to resubscribe your events when the UpdatePanel refreshes.



回答2:

It is because of updatepanel partial postbacks. here is what you need to do.

function pageLoad(sender, args)
{
  $(document).ready(function(){   

   // put all your javascript functions here 

  });
}

I had the same issue and it worked for me. I hope it helps you too.



回答3:

It is because of updatepannel used. Following code is working fine. Just put your jquery code inside the pageLoad event like below

function pageLoad(sender, args) {
     $(document).ready(function () {....}
}


回答4:

i have the same problem, i have solved with this code:

<script type="text/javascript">
    function pageLoad()
    {
        $('#datetimepicker2').datetimepicker();           
    }
</script>


回答5:

Faced same problem. Change

$(document).ready(function() {

to

Sys.Application.add_load(function() {

this will force it to run even on partial postbacck



回答6:

Assuming you are using an UpdatePanel to do the postback and the JS code is attatched to HTML elements within the update panel you need to attach them again when the update panel is loaded. You can hook up your code on the endRequest event:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)

http://msdn.microsoft.com/en-us/library/bb383810.aspx

Keep in mind that if you are using more than one update panel you should check which update panel is refreshed and attach only the events that are needed otherwise you risk events firing more than once.