给动态增加的元素添加事件

今天接触到了一个需要给动态表格添加事件的地方,鼠标滑过左边的表格,将相应的内容显示在右边的div中,试了好久终于出来了,代码如下
<!DOCTYPE html>
<head>
<title>给动态元素添加点击事件</title>
<meta charset="UTF-8">
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<style type="text/css">
.content{
width: 700px;
margin: 0px auto;
padding: 10px;
}
.left{
width: 200px;
height: 400px;
float:left;
margin-left: 20px;
border:solid 1px #666;
}
.right{
width: 300px;
height: 400px;
float:left;
margin-left: 20px;
border:solid 1px #666;
}
.addBcgod{
background-color: #f0f0f0;
color:red;
}
td{
height:18px;
width: 200px;
text-align:center;
}
</style><span style="white-space:pre">	</span>
</head>
<body>
<div class="content">
<div class="left">
<table id="error">
<thead>调用类型</thead>
<tbody></tbody>
</table>
</div>
<div class="right"></div>
</div>
<script type="text/javascript">
//JSon数据
var arr = [{"order":"a","name":"element1"},{"order":"b","name":"element2"},{"order":"c","name":"element3"}];
//首先将tbody里面的元素清空
var tbody = $("#error").find("tbody");
tbody.empty();
//遍历arr里面的元素,每遍历一个元素往tbody里面添加一行表格
$.each(arr,function(index,el){
<span style="white-space:pre">	</span>tbody.append("<tr class='reveal' type='"+index+"'><td>"+el.order+"</td></tr>");
});
//添加鼠标滑过的数据,并将“name”数据显示在右边的div中
$("tbody").on("mouseover",".reveal",function(){
<span style="white-space:pre">	</span>$(this).addClass("addBcgod");
<span style="white-space:pre">	</span>var content = $(this).attr("type");
<span style="white-space:pre">	</span>var detail = arr[content].name;
<span style="white-space:pre">	</span>$(".right").text(detail);
})
$("tbody").on("mouseout",".reveal",function(){
<span style="white-space:pre">	</span>$(this).removeClass("addBcgod");
})
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值