今天接触到了一个需要给动态表格添加事件的地方,鼠标滑过左边的表格,将相应的内容显示在右边的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>