2017-04-17 35 views
1

我在尋找幫助爲什麼此代碼不適用於列的所有標題。此代碼適用於任何列的第一時間,但不會第二次觸發點擊事件。爲什麼$(ColTh).click(function()未被連接到所有th的標頭中?無法綁定所有列標題的點擊事件。僅工作一次

$("table.ui-datepicker-calendar > thead").find("th[scope='col']").each(function() { 
    var ColTh = $(this); 

    $(ColTh).click(function() { 
    var colIndex = $(ColTh).index(); 
    var dateList = []; 
    $(ColTh).closest('table').find('tr').each(function() { 
     var dateTd = $(this).find('td:eq(' + colIndex + ')'); 
     var month = $(dateTd).attr('data-month'); //.trigger('click'); 
     var year = $(dateTd).attr('data-year'); 
     var day = $(dateTd).children(0).text(); 
     if (typeof month != 'undefined') { 
     var monthINT = parseInt(month.trim()); 
     monthINT = monthINT + 1; 
     var newDate = monthINT + '-' + day.trim() + '-' + year.trim(); 
     dateList.push(newDate); 
     } 

    }); 
    $('#itemSchedulerCal').multiDatesPicker('addDates', dateList); 
    dateList = []; 

    }); 

}); 
+0

我想這是因爲日期選擇器功能再次重繪的所有元素,因此,因爲是新的元素並沒有綁定的事件了。你需要使用委託的功能,並沒有必要循環與每個... – DaniP

+2

爲什麼不只是使用委派? (''click','th [scope ='col']「,function(){var ColTh = this,colIndex = $(ColTh).index (); ....})' –

+0

我怎麼可以在這裏使用委託? – youngseagul

回答

0

我沒有以下步驟來實現以上

步驟1:

jQuery(document).ready(function() { 
    $.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker; 
    $.datepicker._updateDatepicker = function (inst) { 
    $.datepicker._updateDatepicker_original(inst); 
    var afterShow = this._get(inst, 'afterShow'); 
    if (afterShow) { 
     // trigger custom callback 
     afterShow.apply((inst.input ? inst.input[0] : null)); 
    } 
} 

});

第2步:

$('#itemSchedulerCal').multiDatesPicker({ 
     showWeek: true, 
     minDate: 0, 
     dateFormat: "m-d-yy", 
    dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], 
    defaultDate: defdate, 
    afterShow: function (inst) 
    { 
     BindClicks(); 
    } 
}); 

第3步:

function BindClicks() { 
// paste all above code 
} 
0

我不知道你的代碼的其餘部分,但你綁定,你可以這樣做:

$("table.ui-datepicker-calendar").on("click", "th[scope='col']", function() { 
    var ColTh = $(this); 

    var colIndex = ColTh.index(); 
    var dateList = []; 
    ColTh.closest('table').find('tr').each(function() { 
    var dateTd = $(this).find('td:eq(' + colIndex + ')'); 
    var month = dateTd.attr('data-month'); //.trigger('click'); 
    var year = dateTd.attr('data-year'); 
    var day = dateTd.children(0).text(); 
    if (typeof month != 'undefined') { 
     var monthINT = parseInt(month.trim()); 
     monthINT = monthINT + 1; 
     var newDate = monthINT + '-' + day.trim() + '-' + year.trim(); 
     dateList.push(newDate); 
    } 

    }); 
    $('#itemSchedulerCal').multiDatesPicker('addDates', dateList); 
    dateList = []; 
}); 

您使用的是ColTh$(ColTh),但ColTh已經是一個jQuery對象,因爲您將它設置爲$(this)。這同樣適用於dateTd

相關問題