防止多次点击触发

Preventing multiple clicks from firing

数据是通过 JSON 动态加载的,所以我必须使用 .on 来加载 .target 并且因为有很多 targets,我必须在里面做一些事情$.getJSON,所以它有几个点击处理程序。

$('.container').on('click', '.target', function(e) {
    e.preventDefault();

    $.getJSON(myData, function(data, status) {
        $('.another-element').on('click', 'a', function(e) {
            e.preventDefault();
        });
    }

});

... 问题是,当单击 .another-element 时,它还会触发 .target 的单击事件,导致其中的所有函数再次出现。我该如何预防?

假设.another-element.target的child,用

停止传播
e.stopPropagation();

event.stopPropagation()

所述

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

更新

No, its not a child. A separate element (which is a sibling) is overlayed on top.

您可以尝试检查目标

$('.container').on('click', '.target', function(e) {
    if(e.target.classList.toString().indexOf('target') == -1){
        return;
    }
    e.preventDefault();

    $.getJSON(myData, function(data, status) {
        $('.another-element').on('click', 'a', function(e) {
            if(e.target.tagName != 'A'){
                return;
            }
            e.preventDefault();
        });
    }

});