开发者

Run ajax scripts on page when navigating with ajax?

开发者 https://www.devze.com 2023-01-01 06:53 出处:网络
I got a bit of an issue in my ASP.NET MVC project. I have a chat div in the bottom right corner (like facebook), and of course I do not want this to reload when navigating to all my navigation is aja

I got a bit of an issue in my ASP.NET MVC project.

I have a chat div in the bottom right corner (like facebook), and of course I do not want this to reload when navigating to all my navigation is ajax.

The problem I am facing is that I use the following code on the top of the view page:

<script type="text/javascript">
$(document).ready(function() {
  $('#divTS').hide();
    $('a#showTS').click(function() {
 $('#divTS').slideToggle(400);
 return false;
  });
});

</script>

The problem is that this code is o开发者_Go百科nly loaded with ajax and does not seem to fire? I would like to run all scripts in the newly loaded view, just as if I hadn't navigated with ajax.

I cannot put this in the site.master as it only loads once and then probably the divs I am trying to hide doesn't exist.

Is there a good way to run scripts in the ajax-loaded div?


You will need to run the scripts in the success callback function of your ajax script. I would recommend you externalizing this into a separate function:

function setupEffects() {
    $('#divTS').hide();
    $('a#showTS').click(function() {
        $('#divTS').slideToggle(400);
        return false;
    });
}

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

And in the success callback of your script call this function:

success: function(result) {
    setupEffects();
}


The Masterpage gets reloaded when you navigate to another View. You can also check if a div exists with $('#div').length > 0.

By the way, "full site" ajax navigation should not be used. Reload your chat on navigation - best put it into a control (makes things easier).

0

精彩评论

暂无评论...
验证码 换一张
取 消