Javascript 事件监听器问题

标签 javascript jquery calendar event-handling jquery-events

假设我们有:

    //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/

相关文章:

javascript - 如何在 TinyMCE 中设置响应式文件管理器返回绝对 url

jquery - 在高度为 :100% 的溢出元素之后放置页脚

c++ - 我不知道如何处理我的日历代码

javascript - Moment.js 从日期获取日期名称

javascript - 是什么导致我的 Access 数据库如此缓慢?

javascript - 谷歌浏览器移动模拟器 : how to force it to open new tab in emulator also?

javascript - 同步倒数计时器和进度条

java - 应该断言保留在测试版本中

javascript - 如何获取仅相对的 offsetParent()

javascript - 如何使用按钮改变javascript代码的风格?