代码之家  ›  专栏  ›  技术社区  ›  nj2237 Rowland Ogwara

即使双击,也只调用一次事件处理程序

  •  0
  • nj2237 Rowland Ogwara  · 技术社区  · 8 年前

    首先,我不想使用 removeEventListener 一旦我的事件被触发。因为,我需要它在用户每次单击元素时激发。

    我也研究过类似的问题。这不是重复,让我解释一下:

    我有一个收藏夹按钮,单击该按钮,会显示我之前已添加书签的项目列表。它起作用了。但当我双击时,由于某种原因,它最终会调用函数两次。

    这是针对其功能的注释的代码:

    document.addEventListener('DOMContentLoaded', function () {
      document.getElementById('favButton').addEventListener('click', function(event) {
        $('#favorites').show(); // shows the bookmarks div element
        $('#front').hide(); // hides the homepage and irrelevant details to current search
        addFavorites(); // populates the bookmarks
      });
    });
    

    并且在 addFavorites() :

    function addFavorites()
    {
        $('#favorites').empty();
        // code to populate bookmarks
    }
    

    每次单击收藏夹时,我都需要它工作,无需重新加载。如果双击,我需要它停止填充收藏夹两次(单击一次,它只填充一次)。

    图片中的问题: addFavorites_called_twice

    观察到一些奇怪的现象: 对于相同的代码,该问题不会出现在Linux上的Chrome 64位版本上,但会出现在Windows上的Chrome 32位版本上(尽管版本号相同)。

    感谢您提供解决此问题的任何指导。谢谢

    1 回复  |  直到 8 年前
        1
  •  2
  •   Taplar    8 年前

    您可以尝试以下方法。

    document.getElementById('favButton').addEventListener('click', function(event){
        //if it has already been clicked, return and don't repeat
        if (this.getAttribute('data-clicked') == 'true') return;
        //marked it as already clicked
        this.setAttribute('data-clicked', true);
    
        $('#favorites').show(); // shows the bookmarks div element
        $('#front').hide(); // hides the homepage and irrelevant details to current search
    
        //if you need this to work multiple times you can make the method
        //return a promise (I assume you are doing some ajax) that will
        //resolve when the request is done
        var promise = addFavorites(); // populates the bookmarks
    
        //we can undo the attribute when it finishes so the logic will repeat
        var thiz = this;
        promise.always(function(){
            thiz.setAttribute('data-clicked', false);
        });
    });