实例:点击显示div里面内容,再次点击隐藏
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.11.3.js"></script> <script type="text/javascript"> $(function () { $("#one h5#two").click(function () { var $content = $(this).next(); if ($content.is(":visible")) { $content.hide(); } else { $content.show(); } }); }); </script> <style type="text/css"> #content { width:150px; background-color:red; } </style> </head> <body> <div id="one"> <h5 id="two">点击点击</h5> <div id="content" style="display:none" >刚好好几款或或或或哈哈哈看到了后来和vsalv</div> </div> </body> </html>
事件冒泡
所谓的冒泡事件就是,如果在某一个对象上触发某一类事件(如click事件),那么此事件会向对象的父级对象传播,并触发父对象上定义的同类事件。事件传播的方向是从最底层到最顶层,类似于水泡从水底浮上来一般。停止事件冒泡:
在jQuery中提供了stopPropagation()方法来停止事件冒泡或者用 return false
例如:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.11.3.js"></script> <script type="text/javascript"> $(function () { $("body").click(function (event) { var tex = $("#msg").html() + "<p>bodybody</p>"; $("#msg").html(tex); // event.stopPropagation(); return false; }); $("#out").click( function (event) { var tex = $("#msg").html() + "<p>外层div</p>"; $("#msg").html(tex); //event.stopPropagation(); return false; }); $("#span").click( function (event) { var tex = $("#msg").html() + "<p>spanspan</p>"; $("#msg").html(tex); //event.stopPropagation(); return false; }); }); </script> <style type="text/css"> body { width:100%; height:680px; border:1px solid red; } #out { width:300px; height:180px; background-color:aqua; } #span { width:300px; height:80px; background-color:red; } #msg { width:300px; height:280px; background-color:beige; } </style> </head> <body> <div id="out">外层div <span id="span">span元素</span> </div> <div id="msg"></div> </body> </html>
阻止默认行为
网页中的元素有自己默认的行为,例如,单击超链接后会跳转,单击‘提交’表单会提交,有时需要阻止元素的默认行为
在jQuery中,提供了preventDefault()方法来阻止元素的默认行为
例如:<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.11.3.js"></script> <script type="text/javascript"> $(function () { $("#Submit1").on("click", function () { var tex = $("#Text1").val(); if (tex=="") { $("#msg").html("<p>用户名不能为空</p>"); event.preventDefault(); //return false; } }); }); </script> </head> <body> <form action="sume.html"> 用户名<input id="Text1" type="text" /><br /> <input id="Submit1" type="submit" value="提交" /> </form> <div id="msg"></div> </body> </html>