简体   繁体   中英

JQuery adding events to dynamically created elements

I know this has been asked before but I can't seem to figure out what I'm doing wrong.

I am just trying to create some dynamic elements and then attach an event to them using only JQuery. The buttons should launch an alert.

http://jsfiddle.net/XGb7w/1/

$(function(){   

    $('#add').on("click",function(){addItem()});


    function addItem() {
        var listItem = '<li>' +  '<button class="checkBtn"></button>' + '<button class="crossBtn"></button>' + '</li>';
        $('ul').append(listItem);
    }


    $('.crossBtn').on("click", function() {
        alert() // Doesn't alert why not?
    });



    $('.checkBtn').on("click", function() {
        alert();// Doesn't alert why not?
    })

});

Thank you.

You can do this if you set the on handler at the document level.

http://jsfiddle.net/fbNY9/

$(function () {

    $('#add').on("click", function () {
        addItem();
    });

    function addItem() {
        var listItem = '<li>' + '<button class="checkBtn" />' + '<button class="crossBtn" />' + '</li>';
        $('ul').append(listItem);
    }

    $(document).on("click",".crossBtn", function () {
        alert(); // Doesn't alert why not?
    });

    $(document).on("click",'.checkBtn', function () {
        alert(); // Doesn't alert why not?
    });

});

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