假设我们有:
//Some vars
function initialSetup(date){
// Call to some functions
}
function populateCalendar(date){
// Call to several function. Task : build and populate a calendar with the date
awesomeFunction() // Have to set click event listener
// If the function call purpose was detected as an update, return value
}
function awesomeFunction(){
// For each day in the calendar, if there is a click, set the displayed date as the correct month, then rebuild the calendar
$(".notInTheMonth").each(function(){
$(this).click(function(e){
//Some process
//Changing date
populateCalendar(processedDate)
updateCalendar(processedVar)
//Some another process
});
});
}
function updateCalendar(updated){
// Jquery transition from the old calendar to the new
// Will put the content of the updated var to replace the content in the table calendar
}
当日历更新时,事件将不会被替换,因此在日历中的单击事件之后,它将更新一次,但不会重新输入awesomeFunction提供的事件监听器
那么问题是什么?
答案 0 :(得分:2)
您可以使用事件委派:
$(document).on('click', '.notInTheMonth', function() {
// Your event handler here
});
将事件侦听器附加到元素时,只要此元素存在于DOM中,侦听器就会存在。因此,当您更新日历时,这些元素将被删除,因此事件监听器也会附加到它们。
使用事件委托,您将设置一个委托(像文档这样的静态元素),负责从您指定的元素类型(任何具有类notInTheMonth
的元素)
检查this
修改强>
如果您构建日历并设置事件侦听器,请确保日历已完成构建过程,然后附加事件侦听器。
1)建立日历</ p>
2)确保日历元素存在于DOM中,然后附加监听器