[英]Click event of jquery is not working when div is dynamically created inside javascript function except on page load it is working
当在javascript函数内部动态创建div时,jquery的click事件不起作用,除非在页面加载时起作用。
在按钮上单击,我将月份传递给setCalenderMonth()函数,该函数创建该月份的html并追加到类似$('#calendar')。html(html);的位置。
HTML:1月2日2月1日3月1日
JS:
function setCalenderMonth(calenderMonth){
let html="";
$('#calendar > div').remove();
html = "<div class='table-responsive-md'><table class='table table-borderless text-center' id='monthTable'><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>";
for(i=0;i<=41;i++){
// if week is over then start a new line
if((i%7)==0){
html += "</tr><tr>";
}
// if week is over then start a new line
if((i>= first_day) && (dy<= last_date)){
html += "<td class='monthDay'><span style='cursor:pointer;padding:2px 6px'>"+ dy +"</span></td>";
dy=dy+1;
}
else {
html += "<td></td>";
} // Blank dates.
} // end of for loop
html += "</tr></table></div>";
$('#calendar').html(html);
}
jQuery的:
$('.monthDay').unbind().on('click',function()
{
$(this).toggleClass('selected');
)};
尝试以下方法:
$('body').on('click', '.monthDay',function()
{
$(this).toggleClass('selected');
)};
并且它将触发您动态添加的所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.