The difference between preventing events e.stopPropagation() and e.preventDefault

e.stopPropagation() and e.preventDefault() are two commonly used methods in event processing. They have different functions:

  1. e.stopPropagation():

    • Function: Prevent further propagation of events in the DOM, that is, stop event bubbling.
    • Usage scenario: When you want to prevent an event from propagating upward from the target element to the parent element or ancestor element, you can call e.stopPropagation().
    • Example:
      document.getElementById('myButton').addEventListener('click', function(e) {
              
              
        e.stopPropagation(); // 阻止点击事件继续向上传播
        console.log('Button clicked');
      });
      
  2. e.preventDefault():

    • Function: Prevent the default behavior of the event.
    • Usage scenarios: Events on some elements have default behaviors, such as clicking a link will jump to a new page, submitting a form will refresh the page, etc. You can prevent these default behaviors from occurring by calling e.preventDefault().
    • Example:
      document.getElementById('myForm').addEventListener('submit', function(e) {
              
              
        e.preventDefault(); // 阻止表单的默认提交行为
        console.log('Form submitted');
      });
      

These two methods can be used alone or in combination, depending on your needs. If you want to prevent event propagation and prevent the default behavior, you can call both methods at the same time:

document.getElementById('myLink').addEventListener('click', function(e) {
    
    
  e.stopPropagation(); // 阻止点击事件继续向上传播
  e.preventDefault(); // 阻止链接的默认跳转行为
  console.log('Link clicked');
});

In general, e.stopPropagation() is used to prevent the propagation of events, while e.preventDefault() is used to prevent the default behavior of events.

Guess you like

Origin blog.csdn.net/z2000ky/article/details/134851153