jquery的冒泡事件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>冒泡事件</title>
<script type="text/javascript" src="../js/jquery.js" ></script>
<script>
    $(function(){
            $("#content span").bind("click",function(){
                var txt=$("#msg").html()+"冒泡事件";
                $("#msg").html(txt);    
            })
            $("#content").bind("click",function(){
                var txt=$("#msg").html()+"冒泡事件";
                $("#msg").html(txt);    
            })
            $("body").bind("click",function(){
                var txt=$("#msg").html()+"冒泡事件";
                $("#msg").html(txt);    
            })
    })
</script>
</head>

<body>
    <div id="content">
        <span>我来触发冒泡</span>
    </div>
    <div id="msg"></div>
</body>
</html>

上面的代码中当你单击span标签的时候就会触发#content和body的单击事件。这种情况称为冒泡事件。

要消除这种情况可以使用事件对象。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>冒泡事件</title>
<script type="text/javascript" src="../js/jquery.js" ></script>
<script>
    $(function(){
            $("#content span").bind("click",function(event){
                var txt=$("#msg").html()+"冒泡事件";
                $("#msg").html(txt);    
                event.stopPropagation();
            })
            $("#content").bind("click",function(){
                var txt=$("#msg").html()+"冒泡事件";
                $("#msg").html(txt);    
            })
            $("body").bind("click",function(){
                var txt=$("#msg").html()+"冒泡事件";
                $("#msg").html(txt);    
            })
    })
</script>
</head>

<body>
    <div id="content">
        <span>我来触发冒泡</span>
    </div>
    <div id="msg"></div>
</body>
</html>

 在阻止默认的事件是可以使用

event.preventDefault() ;或者

return false;或者

event.stopPropagation();

posted @ 2013-03-26 21:12  天道酬勤,坚持!  阅读(224)  评论(0编辑  收藏  举报