tab事件优化-事件代理

<!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 content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,minimal-ui" name="viewport"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>tab点击事件优化</title>
<style>
body,html{margin:0;padding:0;}
.tab_menu{border-bottom:1px solid #e6e6e6;}
.tab_menu a{color:#666;padding:0 10px;line-height:30px;display:inline-block;text-decoration:none;font-size:14px;}
.tab_menu a.crently{color:red;background:#e6e6e6;}
.tab_area{border:1px solid #e6e6e6;width:400px;margin:20px auto 0;}
.tab_content{font-size:12px;}
.tab_content .tab_item{display:none;padding:15px;}
.tab_content .tab_item.block{display:block;}
</style>
</head>

<body>
<!-- tab 1-->
<div class="tab_area">
<div class="tab_menu">
<a href="javascript:;" class="crently">菜单1</a><a href="javascript:;">菜单2</a><a href="javascript:;">菜单3</a><a href="javascript:;">菜单4</a>
</div>
<div class="tab_content">
<div class="tab_item block">内容1</div>
<div class="tab_item">内容2</div>
<div class="tab_item">内容3</div>
<div class="tab_item">内容4</div>
</div>
</div>

<!-- tab 2-->
<div class="tab_area">
<div class="tab_menu">
<a href="javascript:;" class="crently">菜单1</a><a href="javascript:;">菜单2</a><a href="javascript:;">菜单3</a><a href="javascript:;">菜单4</a>
</div>
<div class="tab_content">
<div class="tab_item block">内容1</div>
<div class="tab_item">内容2</div>
<div class="tab_item">内容3</div>
<div class="tab_item">内容4</div>
</div>
</div>


<script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//tab
$(".tab_menu").click(function(e){
var e = e || window.event;
var target = e.target || e.srcElement;
var tab_menu_crent="crently";//当前tab菜单样式
var tab_item_crent="block";//当前tab对应的tab_item样式
if(target.nodeName.toLowerCase() == "a") {
if(!$(target).hasClass(tab_menu_crent))
{
$(target).addClass(tab_menu_crent).siblings("."+tab_menu_crent).removeClass(tab_menu_crent);
$(this).parent().find(".tab_item").eq($(target).index()).addClass(tab_item_crent).siblings("."+tab_item_crent).eq(0).removeClass(tab_item_crent);
}
}
});
});
</script>
</body>
</html>

posted @ 2016-09-11 14:15  异地大光码  阅读(186)  评论(0编辑  收藏  举报