如何将click事件绑定到元素没有使用jquery的特定子节点?

时间:2022-08-26 10:31:55

I have several elements on a page like bottom code.

我在页面上有几个元素,比如底部代码。

<div>
   <a href="#" id="notme">click</a>
   some content 
</div>

They can be clicked and jQuery picks that click. However one of the elements has a a link that is clicked should not be picked as a click of the parent element.

可以单击它们,jQuery选择单击。但是,其中一个元素有一个单击的链接不应该被选为父元素的单击。

$('div:not(#notme)').on('click', function(e) {
    // do something
});

Doesn't seem to work for some reason...

似乎由于某种原因不起作用......

3 个解决方案

#1


0  

Use :has selector to selecting div element has specific child. In :has use :not.

使用:有选择器选择div元素有特定的子元素。在:有用:不。

$("div:has(a:not(#notme))").on("click", function(e) {
    console.log("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <a href="#" id="notme">click</a>
   some content 
</div>
<div>
   <a href="#" >click2</a>
   some content 2
</div>

#2


0  

You may try:

你可以尝试:

$('div').on('click', function(e) {
  if($(e.target).attr("id") !== "notme") {
    // do something
  }
});

#3


0  

$('#notme').on('click', function(e) {
  e.stopPropagation();
});

#1


0  

Use :has selector to selecting div element has specific child. In :has use :not.

使用:有选择器选择div元素有特定的子元素。在:有用:不。

$("div:has(a:not(#notme))").on("click", function(e) {
    console.log("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <a href="#" id="notme">click</a>
   some content 
</div>
<div>
   <a href="#" >click2</a>
   some content 2
</div>

#2


0  

You may try:

你可以尝试:

$('div').on('click', function(e) {
  if($(e.target).attr("id") !== "notme") {
    // do something
  }
});

#3


0  

$('#notme').on('click', function(e) {
  e.stopPropagation();
});