Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - AJAX-loaded JS not rendering

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

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

However, those onClick events aren't firing when I load the partial via 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)}");

The onClick events are not firing. Why is that?

The partial links/_links.html.haml looks like this:

-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);
    })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have a look at the Jquery event handler not working on dynamic content

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(){})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...