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

Categories

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

javascript - How to bind Events on Ajax loaded Content?

I have a link, myLink, that should insert AJAX-loaded content into a div (appendedContainer) of my HTML page. The problem is that the click event I have bound with jQuery is not being executed on the newly loaded content which is inserted into the appendedContainer. The click event is bound on DOM elements that are not loaded with my AJAX function.

What do I have to change, such that the event will be bound?

My HTML:

<a class="LoadFromAjax" href="someurl">Load Ajax</a>
<div class="appendedContainer"></div>

My JavaScript:

$(".LoadFromAjax").on("click", function(event) {
    event.preventDefault();
    var url = $(this).attr("href"),
        appendedContainer = $(".appendedContainer");

    $.ajax({
    url: url,
    type : 'get',
    complete : function( qXHR, textStatus ) {           
        if (textStatus === 'success') {
            var data = qXHR.responseText
            appendedContainer.hide();
            appendedContainer.append(data);
            appendedContainer.fadeIn();
        }
      }
    });

});

$(".mylink").on("click", function(event) { alert("new link clicked!");});

The content to be loaded:

<div>some content</div>
<a class="mylink" href="otherurl">Link</a>
Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

Use event delegation for dynamically created elements:

$(document).on("click", '.mylink', function(event) { 
    alert("new link clicked!");
});

This does actually work, here's an example where I appended an anchor with the class .mylink instead of data - http://jsfiddle.net/EFjzG/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...