jquery阻止冒泡事件:$('span').bind("click",function(event){event.stopPropagation();})(有用源)
冒泡事件就是点击子节点,会向上触发父节点,祖先节点的点击事件。
1 2 3 4 5 6 7 8 9 | <body> <div id= "content" > 外层div元素 <span>内层span元素</span> 外层div元素 </div> <div id= "msg" ></div> </body> |
<script type="text/javascript"> $(function(){ // 为span元素绑定click事件 $('span').bind("click",function(){ var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>";//获取html信息 $('#msg').html(txt);// 设置html信息 }); // 为div元素绑定click事件 $('#content').bind("click",function(){ var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>"; $('#msg').html(txt); }); // 为body元素绑定click事件 $("body").bind("click",function(){ var txt = $('#msg').html() + "<p>body元素被点击.<p/>"; $('#msg').html(txt); }); }) </script>
当点击span时,会触发div与body 的点击事件。点击div时会触发body的点击事件。
如何防止这种冒泡事件发生呢?
修改如下:
<script type="text/javascript"> $(function(){ // 为span元素绑定click事件 $('span').bind("click",function(event){ var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>"; $('#msg').html(txt); event.stopPropagation(); // 阻止事件冒泡 }); // 为div元素绑定click事件 $('#content').bind("click",function(event){ var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>"; $('#msg').html(txt); event.stopPropagation(); // 阻止事件冒泡 }); // 为body元素绑定click事件 $("body").bind("click",function(){ var txt = $('#msg').html() + "<p>body元素被点击.<p/>"; $('#msg').html(txt); }); }) </script>
event.stopPropagation(); // 阻止事件冒泡
有时候点击提交按钮会有一些默认事件。比如跳转到别的界面。但是如果没有通过验证的话,就不应该跳转。这时候可以通过设置event.preventDefault(); //阻止默认行为 ( 表单提交 )。
<script type="text/javascript"> $(function(){ $("#sub").bind("click",function(event){ var username = $("#username").val(); //获取元素的值,val() 方法返回或设置被选元素的值。 if(username==""){ //判断值是否为空 $("#msg").html("<p>文本框的值不能为空.</p>"); //提示信息 event.preventDefault(); //阻止默认行为 ( 表单提交 ) } }) }) </script>
<body> <form action="test.html"> 用户名:<input type="text" id="username" /> <br/> <input type="submit" value="提交" id="sub"/> </form> <div id="msg"></div> </body>
还有一种防止默认行为的方法就是return false。效果一样。
1 <script type="text/javascript"> 2 $(function(){ 3 $("#sub").bind("click",function(event){ 4 var username = $("#username").val(); //获取元素的值 5 if(username==""){ //判断值是否为空 6 $("#msg").html("<p>文本框的值不能为空.</p>"); //提示信息 7 return false; 8 } 9 }) 10 }) 11 </script>
同理,上面的冒泡事件也可以通过return false来处理。
<script type="text/javascript"> $(function(){ // 为span元素绑定click事件 $('span').bind("click",function(event){ var txt = $('#msg').html() + "<p>内层span元素被点击.<p/>"; $('#msg').html(txt); return false; }); // 为div元素绑定click事件 $('#content').bind("click",function(event){ var txt = $('#msg').html() + "<p>外层div元素被点击.<p/>"; $('#msg').html(txt); return false; }); // 为body元素绑定click事件 $("body").bind("click",function(){ var txt = $('#msg').html() + "<p>body元素被点击.<p/>"; $('#msg').html(txt); }); }) </script>
原文地址:http://www.cnblogs.com/jiqing9006/archive/2012/09/11/2679831.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步