代码之家  ›  专栏  ›  技术社区  ›  mmvsbg

jquery:单击元素,不包括单击子元素

  •  4
  • mmvsbg  · 技术社区  · 7 年前

    我正在努力找到正确的jquery选择器来点击某个元素。以下是我的HTML:

    <label class="title-label" for="me">Some Title<i class="fa fa-times del-class"></i></label>
    

    我有两个单独的jquery侦听器:

    $(document).on("click", ".title-label", function (e) { //magic happens here
    

    另一个是:

    $(document).on("click", ".del-class", function (e) { //the whole label gets deleted
    

    当我点击我发送的标签时 .ajax 向服务器发出请求后,魔法就发生了。还有一点 i 用于删除整个标签的图标。但是,当我单击 .del-class 图标,它首先触发单击 .title-label 它将请求发送到服务器,然后魔术发生,标签被删除。图标需要保持在标签内,但当我点击它时,它不应该触发点击标签和魔法,而是立即删除标签。

    我尝试了各种尝试来包括 :not 选择器如下:

    :not('.del-class') .title-label
    

    但两者都会被触发。有什么线索,在这种情况下,正确的选择器是什么?

    3 回复  |  直到 7 年前
        1
  •  6
  •   Eddie    7 年前

    你可以用 e.stopPropagation() 为了防止事件在DOM树上冒泡,防止任何父处理程序收到该事件的通知。

    $(document).on("click", ".title-label", function(e) {
      console.log('title-label click');
    });
    
    $(document).on("click", ".del-class", function(e) {
      e.stopPropagation();  //Add
      console.log('del-class click');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label class="title-label" for="me">Some Title<i class="fa fa-times del-class"> Other text </i></label>
        2
  •  0
  •   Mihai T    7 年前

    event.target 是否是图标并在 if/else

    $(document).on("click", ".title-label", function(e) {
    let tgt = e.target
          if (!$(tgt).is('.del-class ') ) {
              console.log('do magic now')
            }
            else {
              console.log('delete label straight away')
            }
        //or
        
        !$(tgt).is('.del-class ') ? console.log('do magic now') : console.log('delete label straight away')
            
    })
    i {
      width: 20px;
      height: 20px;
      background: Red;
      display: inline-block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label class="title-label" for="me">Some Title<i class="fa fa-times del-class"></i></label>
        3
  •  -2
  •   Teobis    7 年前

    如果我理解正确,您有两个元素,其中一个在另一个元素中,如果您需要两个独立的侦听器,您需要在子元素上使用event.stoppropagation()。

    https://jsfiddle.net/xpvt214o/239539/

    $('.parent_div_click').on('click',function(event){
        console.log('click in parent');
    });
    $('.child_i_click').on('click',function(event){
            event.stopPropagation();
        console.log('click in child');
    });
    

    希望这有帮助