应该如何处理Ajax加载的局部视图中的javascript? [英] How should javascript in an ajax loaded partial view be handled?

查看:91
本文介绍了应该如何处理Ajax加载的局部视图中的javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC中,在通过Ajax加载的部分视图上运行Javascript的首选模式是什么?

In ASP.NET MVC, what is the preferred pattern for running Javascript on a partial view that is loaded via Ajax?

例如,假设您需要在部分视图中连接一些点击事件.

For example, suppose you need to wire up some click events in your partial view.

当然,在部分视图中放置这样的内容是行不通的,因为在部分视图加载Ajax后不会触发文档就绪事件.

Of course, putting something like this in the partial view would not work, because the document ready event won't fire after the partial view is Ajax loaded.

<script type="text/javascript">
    $(function() {
        $("a.foo").click(function() {
            foo();
            return false;
        });
    });
</script>

我想类似的方法可能有用,但是安全吗?

I suppose something like this might work, but is it safe?

<script type="text/javascript">
    $("a.foo").click(function() {
        foo();
        return false;
    });
</script>

我一直使用的模式是在加载部分代码后从父视图运行任何Javascript,如下所示:

The pattern I have been using has been to run any Javascript from my parent view after loading the partial, like this:

$.get(url, function(html) {
    $("#partialDiv").html(html);

    // Now that the partial has loaded...
    RegisterClicks();
});

但是我一直在通过示例,并注意到他们只是将其点击注册代码直接插入部分视图中.

But I've been working through this example, and noticed that they simply put their click registering code inline in the partial view.

这是普遍采用的安全模式吗?在脚本运行之前,如何确定部分视图的DOM已经完成加载?

Is this a generally safe pattern to adopt? How can I be sure that the DOM for the partial view has finished loading before my script runs?

推荐答案

jQuery .on()函数应该可以解决问题,不是吗?它应该适用于动态添加的内容.

The jQuery .on() function should do the trick, shouldn't it? It should work for dynamically added content.

将此内容作为全部内容的一部分

Have this available as part of the full content

<script type="text/javascript">
    $(function() {
        $("#partialContent").on("click", "a.foo", function() {
            foo();
            return false;
        });
    });
</script>

<div id="partialContent">
   <a href="#" class="foo">Link 1</a>
   <a href="#" class="foo">Link 2</a>
   <!-- More dynamic content -->
</div>

这篇关于应该如何处理Ajax加载的局部视图中的javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆