preventDefault()阻止元素默认事件和 stopPropagation()阻止元素事件冒泡

标签:2024-05-17 19:14:16

preventDefault()函数: a标签,radio、checkbox复选框等表单元素,div没有默认事件

示例:

<input type="checkbox" id="checkbox"/>
<a href="http://www.good1230.com/" target="_black">HLJ的博客</a>
<script>
let dom = document.querySelector("#checkbox")
  dom.addEventListener("click", function(event) {
      console.log("preventDefault() 阻止了复选框选择事件!")
      event.preventDefault();
  }, false);
let dom2 = document.querySelector("a");
  dom2.addEventListener("click",function(e){
    console.log("preventDefault() 阻止了a标签跳转事件!")
    e.preventDefault()
  },false);
</script>

stopPropagation()函数

<div id="c" onclick="alert(1)">
  <div id="c2" onclick="alert(2)">
    <input type="button" id="c3" value="点击" onclick="alert(3)">
  </div>
</div>

点击button按钮时,浏览器会先后弹出3, 2, 1,这时我们可以用stopPropagation()来阻止触发两个div上的事件

let dom = document.getElementById('c3')
  dom.addEventListener('click',function(e){
    e.stopPropagation()
  },false);
原文出处:http://www.dongblog.com/notes/64.html
来源:博客网 转载请注明出处!

活跃用户

天日十口天口
Ta还没有签名
雾里
Ta还没有签名
霓笑
Ta还没有签名
???????????
Ta还没有签名

友情链接


Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093

Warning: Smarty error: unable to read resource: "../../../templates/default/./common/foot/footer_index.htm" in /usr/home/hyu3925200001/htdocs/common/smarty/Smarty.class.php on line 1093