检测特定 div 的任何嵌套元素中的点击事件

Detect click event in any nested element of an specific div

我需要能够检测到 class 引用的特定容器内发生的任何点击,如果用户点击任何嵌套元素,我应该能够检测到点击并更新标志

<div class="container" >
   <div class="x1">
   <div class="x2">
      <div class="">
         <span class="">
         <ul class="">
   </div>
</div>

我尝试使用 jquery,但我更喜欢使用 backbone。

//$(document).on('click','.container', function(e){
//$('.container').delegate("div", "click", function(e) {

不确定当用户单击 div 中包含容器 class 的某些嵌套元素时我需要使用什么事件。基本上,我需要更新一个标志,以防用户在 div 之外单击,但我不想在监听整个主体的事件处理程序上有很大的范围。

也许是这个?:

$(document).on('click','.container *', function(e){
console.log(e.target);
});

jQuery 的优点在于,您可以使用与 CSS 相同的选择器,因此我使用 .container * 来定位容器内的所有元素。

我使用了 jquery .children() 方法。查看 this code pen

var flag = 'whatever';

$(.container).children().on('click', function() {
  flag = 'updated';
});

本质上,对于 class 容器(在本例中为 div)任何元素的所有子元素,添加一个事件处理程序。

既然你要了一个 Backbone 例子,下面是如何监听对 div 及其 children.

的点击
var View = Backbone.View.extend({
    className: "my-test-view",
    template: '<div class="container"><div class="x1"><div class="x2">test</div></div></div>',
    events: {
        'click .container': 'onClick',
    },

    render: function() {
        this.$el.empty().append(this.template);
        return this;
    },

    onClick: function(e) {
        console.log("clicked on", e.target, " triggered from ", e.currentTarget);
    },
});

var view = new View();

$("body").append(view.render().el);

单击 test 文本应输出:

clicked on <div class=​"x2">​test​</div>​  triggered from  <div class=​"container">​…​</div>​

与jQuery,以上(大致)等同于:

$('.my-test-view').on('click', '.container', function(e) {
    console.log("clicked on", e.target, " triggered from ", e.currentTarget);
});

但对于大多数情况,这应该足够了:

$('.container').on('click', function(e) {
    console.log("clicked on", e.target, " triggered from ", e.currentTarget);
});

不要使用 .children().on(...),因为这会为每个 child 创建一个新的侦听器,而且效率很低。

检测 div 外的点击是完全不同的,有很多方法可以实现,但 none 是完美的。

参见:

  • Backbone view with custom event to detect clicks outside of it
  • How to detect a click outside an element?
  • Use jQuery to hide a DIV when the user clicks outside of it

就个人而言,我使用了 focusblur 事件(不要忘记元素上的 tabindex="-1")。