代码之家  ›  专栏  ›  技术社区  ›  Nicolas Frbezar

Javascript事件侦听器问题

  •  0
  • Nicolas Frbezar  · 技术社区  · 9 年前

    假设我们有:

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

    那么有什么问题吗?

    1 回复  |  直到 3 年前
        1
  •  2
  •   kapantzak    9 年前

    您可以使用事件委派:

    $(document).on('click', '.notInTheMonth', function() {
       // Your event handler here
    });
    

    将事件侦听器附加到元素时,只要该元素存在于DOM中,侦听器就存在。因此,当您更新日历时,这些元素会被删除,因此事件侦听器也会附加到这些元素上。

    通过事件委托,您将设置一个委托(一个静态元素,如文档),负责从指定的元素类型(具有类的任何元素)中侦听任何冒泡事件 notInTheMonth )

    检查 this

    编辑

    如果您构建日历并设置事件侦听器,则每次都要确保日历已完成其构建过程,然后附加事件侦听器。

    1) 创建日历

    2) 确保DOM中存在日历元素,然后附加侦听器