简体   繁体   English

将Click函数添加到动态生成的div jquery中

[英]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. 我是JQuery的新手,我遇到了将函数绑定到动态生成的div的问题。

Essentially the user clicks a button which adds a couple divs to a container and also changes the background color of that container. 用户基本上单击一个按钮,将一对div添加到容器中,并更改该容器的背景颜色。 I want them to have the option to remove what they added by clicking on one of the divs. 我希望他们可以选择通过单击其中一个div来删除他们添加的内容。

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. 但无论出于何种原因,当我点击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. 通过它的声音,当jQuery尝试绑定处理程序时,你的.course-delete元素不存在 - 因为你的div是以后动态创建的。 If this is the issue, then event delegation will be your saviour: https://learn.jquery.com/events/event-delegation/ 如果这是问题,那么事件委托将成为你的救星: 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. 将click事件委派给最近的容器以获得更好的性能。

$("#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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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