jQuery事件绑定和解绑、事件冒泡与阻止事件冒泡

事件的绑定和解绑

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://www.jb51.net/js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function () { $('#div1').bind('mouseover click',function (event) {//绑定事件:移动到div块上和点击 alert($(this).html); $(this).unbind('mouseover');//取消鼠标移动到上面的事件 }) }) </script> <style type="text/css"> #div1{ background-color: #f6b544; width: 100px; height: 100px; } </style> </head> <body> <div> </div> </body> </html>

绑定事件:移动到div块上和点击

解绑事件:取消鼠标移动到上面的事件

事件冒泡-阻止事件冒泡

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://www.jb51.net/js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function () { $('.son').click(function () { alert(1); }); $('.father').bind('click',function () { alert(2); }); $('.grandfather').bind('click',function () { alert(3); }); }) </script> <style type="text/css"> .grandfather{ width: 300px; height: 300px; background-color: green; } .father{ width: 200px; height: 200px; background-color: gold; } .son{ width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div> <div> <div> </div> </div> </div> </body> </html>

定义了三个div,在son点击一下弹出1,father点击一下弹出2,grandfather点击一下弹出3,如果我们点击son一下,那么会依次弹出123,点击father一下会依次弹出二三。

按照标签往上传到它的父级

事件冒泡有时候不需要,需要阻止,通过eventstopPropagation()来阻止

$('.son').click(function (event) {//event就是一个事件对象 //用这个事件对象就能使用事件对象的方法 alert(1); event.stopPropagation();//阻止事件对象冒泡 });

除了阻止事件冒泡,还要阻止一些默认行为,开发中直接return false就行。

$('.father').bind('click',function () { alert(2); //阻止事件冒泡和阻止默认行为的同意写法 return false; });

弹框

点击弹框外面关闭弹框

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://www.jb51.net/js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function () { $('#btn').click(function () { // alert(2); $('.pop_con').fadeIn(); // alert(1); return false;//阻止事件,冒泡 }); $(document).click(function () { $('.pop_con').fadeOut(); }) }) </script> </head> <style type="text/css"> .pop{ position: fixed; width: 500px; height: 300px; background-color: #fff; border: 3px solid #000; left: 50%; top: 50%; margin-left: -250px; margin-top: -150px;/*拉回去*/ z-index: 2; } .mask{ position: fixed; width: 100%; height: 100%; background-color: #000000; opacity: 0.3; filter:alpha(opacity=30);/*兼容ie浏览器的*/ left: 0; top: 0; z-index: 1;/*z-index设置现实层级*/ } .pop_con{ display: none;/*因为pop_con包含住了mask和pop,所以设置了这个之后,他们就隐藏了*/ } </style> <body> <input type="button" value="弹出"> <div> <div> 弹框里面的文字 </div> <div></div> </div> </body> </html>

如果不组织事件冒泡的话,点击之后,弹框出现之后,就会直接隐藏,只有阻止之后,才能点击外框的document或者mask才能隐藏弹框。

更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery操作json数据技巧汇总》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》及《jquery选择器用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/97b5ca5d37e1d4bffee6a1d21c0cab4f.html