假设我们有:
//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
提供的事件监听器。
那么问题出在哪里呢?
最佳答案
您可以使用事件委托(delegate):
$(document).on('click', '.notInTheMonth', function() {
// Your event handler here
});
当您将事件监听器附加到元素时,只要该元素存在于 DOM 中,监听器就存在。因此,当您更新日历时,这些元素将被删除,因此事件监听器也会附加到它们。
通过事件委托(delegate),您可以设置一个委托(delegate)(类似文档的静态元素),该委托(delegate)负责监听您指定的元素类型(任何具有 notInTheMonth
类的元素)的冒泡事件
检查this
编辑
如果您每次构建日历并设置事件监听器,请确保日历已完成其构建过程,然后附加事件监听器。
1)构建日历
2) 确保日历元素存在于 DOM 中,然后附加监听器
关于Javascript 事件监听器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36978097/