简体   繁体   中英

Adding Click Function to Dynamically Generated div jquery

I am fairly new to JQuery and I am having issues with binding functions to a dynamically generated div.

Essentially the user clicks a button which adds a couple divs to a container and also changes the background color of that container. I want them to have the option to remove what they added by clicking on one of the divs.

I have this function that I thought should do that:

$('.course-delete').click(function() {
    var course = $(this).parent();
    alert("hello");
    $(course).css('background', "#fff");
    $(course).empty();  
});

But for whatever reason nothing happens when I click the div. If anyone knows what is going on I would appreciate it.

By the sounds of it, your .course-delete elements don't exist when jQuery attempts to bind the handler - because your divs are created dynamically later. If this is the issue, then event delegation will be your saviour: https://learn.jquery.com/events/event-delegation/

$(document).on('click', '.course-delete', function () {
    /* do delete stuff here */
});

Delegate the click event to closest container for better performance.

$("#divcontainer").on("click", ".course-delete", function() {

});

You could also..

//Create your new DIV
var newDiv=$('<div />',{
html:'This is sample HTML', // add your HTML
click:function(){
// your click event handler
}
});

and then add to your document like...

newDiv.appendTo('body');//or any selector you want to append to. Use prependTo if you want it as the first element of the container.

So when combined, you can write like this...

$('<div />',{// you can set attributes and other stuff here
    html:'This is sample HTML', // add your HTML
    click:function(){
    // your click event handler
    }
 }).appendTo(container);

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