Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...