简体   繁体   English

如何选择一个类但不选择其内部元素?

[英]How do I select a class but not its inside element?

Say I have 说我有

<div id="mydiv">
  <div class="myclass">
       <span class="otherclass"></span>
       and many other classes...
  </div>
</div>

I want to capture the click event on .mydiv but not inside .myclass. 我想在.mydiv上捕获click事件,但不在.myclass中捕获。

I tried .mydiv:not(.myclass) but it doesn't seem to work. 我试过.mydiv:not(.myclass)但它似乎没有用。 I think it's because I might be clicking on the otherclass so the :not(.myclass) is not working. 我想这是因为我可能点击了其他类,所以:not(.myclass)不起作用。 How can I get the area I want to get? 我怎样才能得到我想要的区域? Thanks! 谢谢!

make #mydiv clickable, do whatever you wish, and stop event propagation from .myclass , so the event will not bubbleup from myclass to mydiv make #mydiv clickable,做任何你想做的事情,并从.myclass停止事件传播,所以事件不会从myclass到mydiv冒泡

     $('#mydiv').click(function(){
        // do anything
     })

    // stop event propagation
     $('.myclass').click(function(e){
        e.stopPropagation();
        })

You can click on mydiv id and write your code in that function and on .myclass click event you simply write return false to stop further execution of function. 您可以单击mydiv id并在该函数和.myclass单击事件中编写代码,您只需编写return false以停止进一步执行函数。

$('#mydiv').click(function(){
    // stuff your code here
});

//Use `return false` instead of `e.stopPropagation();`
$('.myclass').click(function(e){
  return false;
})

e.stopPropagation() is dangerous please read Documentation e.stopPropagation()很危险,请阅读文档

Calling .off() will remove an event handler 调用.off()将删除事件处理程序

    $("#mydiv").on('click', function () {
        alert("You clicked mydiv");
    });

    $(".myclass").off('click', function () {
    });
           or like this

   $(".myclass").off();

JS FIDDLE JS FIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM