簡體   English   中英

當在javascript函數內部動態創建div時,jquery的click事件不起作用,但在頁面加載時它起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM