[JS basics] e.stopPropagation() prevents events from bubbling

e.stopPropagation() prevents the event from bubbling

Initial example

  <table border="1">
    <tr>
      <td><span>冒泡事件测试</span></td>
      <td><span>冒泡事件测试2</span></td>
    </tr>
  </table>
    $('table').on('click', function(e) {
    
    
      alert('table alert!')
    })

    $('tr').on('click', function() {
    
    
      alert('tr alert') 
    })

    $('span').on('click', function() {
    
    
      alert('span alert!')
    })

Initial effect

Insert picture description here

We will see this situation: span alert -> td alert -> table
alert. This is called event bubbling. That is, from bottom to top, from inside to outside, the events are triggered in sequence.

Sometimes we don’t want events to bubble up, what should we do?

    $(function() {
    
    
      $('table').on('click','span',function(e) {
    
    
        alert('span alert!')
        e.stopPropagation();
      })
      $('table').on('click', function() {
    
    
        alert('table alert!')
      })
    })

In this way, when the span is clicked, the "span alert!" dialog box will end, and then the event bubbling is prohibited, and the "table alert!" dialog box will not be triggered.

If you want to get event-related information, you must add an e object to the anonymous method, e is the event object

Guess you like

Origin blog.csdn.net/weixin_43352901/article/details/108401452