jQuery('#warning').click(function() {
  console.log('clicked at warning');
});

jQuery('#content').click(function() {
  console.log('clicked at content');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
  <div id="content">This is the content</div>
  dsfdfsdsfdsfdsfdsfdsfdsf
</div>

Biola: https://jsfiddle.net/73jykhj0/

Sayangnya mengeklik content juga memicu klik di warning. Bagaimana cara menghilangkan klik di warning?

1
John Smith 18 Agustus 2017, 10:56

2 jawaban

Jawaban Terbaik

Cegah acara meledak menggunakan event.stopPropagation()

jQuery('#warning').click(function() {
  console.log('clicked at warning');
});

jQuery('#content').click(function(event) {
  event.stopPropagation()
  console.log('clicked at content');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
  <div id="content">This is the content</div>
  dsfdfsdsfdsfdsfdsfdsfdsf
</div>

Atau, Anda dapat memeriksa target acara menggunakan event.target lalu lakukan yg diperlukan.

jQuery('#warning').click(function(event) {
  if ($(event.target).is('#content')) {
    return;
  }
  console.log('clicked at warning');
});

jQuery('#content').click(function() {
  console.log('clicked at content');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
  <div id="content">This is the content</div>
  dsfdfsdsfdsfdsfdsfdsfdsf
</div>
7
Satpal 18 Agustus 2017, 08:03

Lihat di bawah. Menambahkan return false untuk klik pada konten.

jQuery('#warning').click(function() {
    alert('clicked at warning');
});

jQuery('#content').click(function() {
    alert('clicked at content');
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning">
    <div id="content">This is the content</div>
    dsfdfsdsfdsfdsfdsfdsfdsf
</div>
2
Gerard 18 Agustus 2017, 07:58