[英]Adding Click Function to Dynamically Generated div jquery
我是JQuery的新手,我遇到了將函數綁定到動態生成的div的問題。
用戶基本上單擊一個按鈕,將一對div添加到容器中,並更改該容器的背景顏色。 我希望他們可以選擇通過單擊其中一個div來刪除他們添加的內容。
我有這個功能,我認為應該這樣做:
$('.course-delete').click(function() {
var course = $(this).parent();
alert("hello");
$(course).css('background', "#fff");
$(course).empty();
});
但無論出於何種原因,當我點擊div時沒有任何反應。 如果有人知道發生了什么,我會很感激。
通過它的聲音,當jQuery嘗試綁定處理程序時,你的.course-delete元素不存在 - 因為你的div是以后動態創建的。 如果這是問題,那么事件委托將成為你的救星: https : //learn.jquery.com/events/event-delegation/
$(document).on('click', '.course-delete', function () {
/* do delete stuff here */
});
將click事件委派給最近的容器以獲得更好的性能。
$("#divcontainer").on("click", ".course-delete", function() {
});
你也可以......
//Create your new DIV
var newDiv=$('<div />',{
html:'This is sample HTML', // add your HTML
click:function(){
// your click event handler
}
});
然后添加到您的文檔,如...
newDiv.appendTo('body');//or any selector you want to append to. Use prependTo if you want it as the first element of the container.
所以當合並時,你可以像這樣寫...
$('<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.