如何从点击事件中排除 child class?

How can I exclude child class from click event?

我想从点击函数中排除 class noclick:

$( ".click" ).on( "click", ":not(.noclick *)", function() {
  console.log( $( this ).text() );
});
.noclick{
  background-color:pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr class="click">
    <th>Click</th>
    <th>Click</th>
    <th class="noclick">Nothing should happen here</th>
  </tr>
</table>

只需删除 ":not(.noclick *)"

中的星号

这使得 .noclick 的后代事件不会触发该函数,但不会阻止 .noclick 本身。

$( ".click" ).on( "click", ":not(.noclick)", function() {
  console.log( $( this ).text() );
});
.noclick{
background-color:pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr class="click">
    <th>Click</th>
    <th>Click</th>
    <th class="noclick">Nothing should happen here</th>
  </tr>
</table>

下面的代码应该可以工作。

$( ".click" ).on( "click", function() {
  if ($( this ).has( ".noclick" ).length == 0)
      console.log( $( this ).text() );
});

这也适用于动态添加的 tr.click:

$(document).on("click", ".click *:not(.noclick)", function() {
  console.log($(this).text());
});
.noclick {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr class="click">
    <th>Click</th>
    <th>Click</th>
    <th class="noclick">Nothing should happen here</th>
  </tr>
</table>