AJAX加载的JS无法呈现 [英] AJAX-loaded JS not rendering

查看:91
本文介绍了AJAX加载的JS无法呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Rails应用程序加载了一个包含链接的部分文件,并加载了一个脚本,该脚本为每个链接创建onClick事件.

My Rails app loads a partial which contains links, and a script loaded that creates onClick events for each link.

然后正常加载页面(而不是通过AJAX)时,这些链接可以正常显示.

Those links render fine when then page is loaded normally (not via AJAX).

但是,当我通过AJAX加载部分内容时,那些onClick事件不会触发.

However, those onClick events aren't firing when I load the partial via AJAX.

当我对load_links_url进行ajax调用时,其视图包含以下内容:

When I do an ajax call to load_links_url, whose view contains this:

$("#my_div").html("#{j render('links/links', the_links: @links)}");

onClick事件未触发.为什么会这样?

The onClick events are not firing. Why is that?

部分links/_links.html.haml看起来像这样:

-links.each do |link|
    =link_to link.name, "javascript:;", id: "select_link_#{link.id}", class: "select-link", "data-id" => link.id, "data-name" => link.name

:javascript
    $(".select-link").click(function() {
        var id = $(this).data("id");
        var thename = $(this).data("name");
        $('#link_name_header').html(thename);
        $('#creative_session_link_id').val(id);
    })

推荐答案

看看总而言之,对于动态添加的内容,请将.on与适当的选择器一起使用以进行事件委托.就像您的情况一样:

In summary, for dynamically added content, use .on with proper selector for event delegation. Like, in your case:

$('#my_div').on('click', '.select-link', function(){})
or
$(document.body).on('click', '.select-link', function(){})

这篇关于AJAX加载的JS无法呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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