简体   繁体   English

使用ajax导航时在页面上运行ajax脚本?

[英]Run ajax scripts on page when navigating with ajax?

I got a bit of an issue in my ASP.NET MVC project. 我在ASP.NET MVC项目中遇到了一个问题。

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. 我在右下角(如Facebook)聊天DIV,当然我不希望浏览到我的所有导航时,这个重载是阿贾克斯。

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 only loaded with ajax and does not seem to fire? 问题在于此代码仅使用ajax加载,似乎不会触发? I would like to run all scripts in the newly loaded view, just as if I hadn't navigated with ajax. 我想在新加载的视图中运行所有脚本,就像我没有使用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. 我不能将它放在site.master中,因为它只能加载一次,然后可能我要隐藏的divs不存在。

Is there a good way to run scripts in the ajax-loaded div? 有没有一种好的方法可以在Ajax加载的div中运行脚本?

The Masterpage gets reloaded when you navigate to another View. 导航到另一个视图时,将重新加载母版页。 You can also check if a div exists with $('#div').length > 0 . 您还可以检查$('#div').length > 0是否存在$('#div').length > 0

By the way, "full site" ajax navigation should not be used. 顺便说一句,不应使用“完整站点” ajax导航。 Reload your chat on navigation - best put it into a control (makes things easier). 在导航上重新加载聊天-最好将其放入控件中(使事情变得更容易)。

You will need to run the scripts in the success callback function of your ajax script. 您将需要在ajax脚本的成功回调函数中运行这些脚本。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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