jQuery学习笔记13-事件冒泡和默认行为

桃扇骨 2024-04-17 18:47 129阅读 0赞
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>jQuery事件冒泡和默认行为</title>
  6. <style>
  7. *{
  8. margin: 0;
  9. padding: 0;
  10. }
  11. .father{
  12. width: 200px;
  13. height: 200px;
  14. background-color: #FFEE00;
  15. }
  16. .son{
  17. width: 100px;
  18. height: 100px;
  19. background-color: red;
  20. }
  21. </style>
  22. <script src="jQuery/jquery-1.12.4.js"></script>
  23. <script>
  24. $(function () {
  25. /*
  26. * 1.什么是事件冒泡
  27. * 给标签及上级绑定事件时,标签触发事件同时会触发上级标签的事件
  28. * 如下所示,son属性div为father属性div的子标签。
  29. * son属性的div绑定弹出son弹框的点击事件,
  30. * father属性的div绑定弹出father弹框的点击事件
  31. * 此时我们点击son属性的div,会同时弹出son弹框及father弹框
  32. * */
  33. // $(".son").click(function () {
  34. // alert("son")
  35. // });
  36. // $(".father").click(function () {
  37. // alert("father")
  38. // });
  39. /*
  40. * 2.阻止事件冒泡
  41. * 方法一、return false
  42. * 方法二、函数添加event回调,函数体添加event.stopPropagation()
  43. * 点击son属性的div,不会弹出father弹框
  44. * */
  45. //方法一、return false
  46. // $(".son").click(function () {
  47. // alert("son");
  48. // return false
  49. // });
  50. //方法二、函数添加event回调,函数体添加event.stopPropagation()
  51. $(".son").click(function (event) {
  52. alert("son");
  53. event.stopPropagation();
  54. });
  55. $(".father").click(function () {
  56. alert("father");
  57. });
  58. /*默认行为
  59. * html中有些标签点击后,就有默认行为。比如点击a标签,就会跳转指定连接
  60. * form表单中,点击提交按钮,就会跳转到指定地址
  61. * 阻止默认行为
  62. * 点击a标签只执行jQuery绑定的事件,不执行链接跳转
  63. * 方法一、return false
  64. * // 方法二、函数添加event回调,函数体添加event.preventDefault()
  65. * */
  66. // 给a标签添加点击事件后,点击弹框的确定按钮,就会跳转到百度首页。
  67. // 现在需要点击确定后不进行跳转,此时就要去除a标签的默认事件
  68. // 方法一、return false
  69. $("a").click(function () {
  70. alert("注册");
  71. return false
  72. });
  73. // 方法二、函数添加event回调,函数体添加event.preventDefault()
  74. $("a").click(function (event) {
  75. alert("注册");
  76. event.preventDefault();
  77. })
  78. })
  79. </script>
  80. </head>
  81. <body>
  82. <div class="father">
  83. <div class="son">
  84. </div>
  85. </div>
  86. <a href="https://www.baidu.com/">注册</a>
  87. <form action="https://www.taobao.com/">
  88. <input type="text">
  89. <input type="submit">提交
  90. </form>
  91. </body>
  92. </html>

发表评论

表情:
评论列表 (有 0 条评论,129人围观)

还没有评论,来说两句吧...

相关阅读