event.stopPropagation()和event.preventDefault()

一、event.stopPropagation();阻止冒泡事件

$(document).ready(function(){
  $("span").click(function(event){
    event.stopPropagation();
    alert("The span element was clicked.");
  });
  $("p").click(function(event){
    alert("The p element was clicked.");
  });
  $("div").click(function(){
    alert("The div element was clicked.");
  });
});

阻止click事件冒泡到父元素;当点击span标签时只会弹出

The span element was clicked.

而当点击p标签时,则会弹出

The p element was clicked.随后弹出,The div element was clicked.

二、event.preventDefault() 方法阻止元素发生默认的行为。

例如阻止打开url,当点击提交按钮时阻止对表单的提交等等

Go to W3Cschool.cc



你可能感兴趣的:(event.stopPropagation()和event.preventDefault())