简体   繁体   中英

Issue with binding event handler to dynamically generated divs

I have a problem with displaying the id of the clicked div on the screen in an alert window. I am pretty confident this is because of the order of the controls and event handlers being added to the page, however after trying different ways I am unable to get this to work. Unfortunately I can't post reproducible code due to the div's being created from an ajax get request.

$(document).ready(function () {
    $.getJSON('ClientPortal/GetSkills', function (data) {
        var test = 'poo';
        $.each(data, function (data) {
            $('#flipContainer').append("<div class=flip id='" + this.Value + "' value='" + this.Value + "'>" + this.Text + "<//div>");
        })
    })
})

$(document).ready(function () {
    $(".flip").on('click', function () {
        alert($(this).attr("id"));
     })
})

Try this :

$(document).ready(function () {
    $("#flipContainer").on("click", ".flip", function () {
        alert($(this).attr("id"));
     })
})

You effectively have to base you click-binding on an element existing when the DOM ready event fires... But with this syntax, you delegate the binding on an existing element but it applies to another element contain in the first one... See the jQuery documentation for on (for line "selector") : http://api.jquery.com/on/#on-events-selector-data-handlereventObject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM