使用自定义属性来完成:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.table{
text-align: center;
}
.hide{
display: none;
}
.modal{
position: fixed;
background-color: white;
width: 500px;
height: 400px;
top:50%;
left:50%;
margin-left: -250px;
margin-top: -300px;
z-index:10;
}
.shadow{
position: fixed;
top:0;
left:0;
right:0;
bottom:0;
background-color: gray;
opacity: 60%;
z-index:9;
}
</style>
</head>
<body>
<div>
<input id="add" type="button" value="添加" />
</div>
<table class="table" border="1">
<thead>
<tr>
<td>IP</td>
<td>PORT</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr>
<td target="ip">1.1.1.11</td>
<td target="port">80</td>
<td>
<a class="edit">编辑</a> | <a>删除</a>
</td>
</tr>
<tr>
<td target="ip">1.1.1.12</td>
<td target="port">80</td>
<td>
<a class="edit">编辑</a> | <a>删除</a>
</td>
</tr>
<tr>
<td target="ip">1.1.1.13</td>
<td target="port">80</td>
<td>
<a class="edit">编辑</a> | <a>删除</a>
</td>
</tr>
</tbody>
</table>
<div class="modal hide">
<div>
<input type="text" name="ip"/>
<input type="text" name="port"/>
</div>
<div>
<input id="cancel" type="button" value="取消" />
</div>
</div>
<div class="shadow hide"></div>
<script src="jquery-1.12.4.js"></script>
<script>
//点击添加按钮,将蒙版层和模态框的hide样式去除
$("#add").click(function(){
$(".modal,.shadow").removeClass('hide');
});
//点击取消按钮,将蒙版层和模态框的hide样式加上
$("#cancel").click(function(){
$(".modal,.shadow").addClass('hide');
});
//点击编辑
$('.edit').click(function(){
$(".modal,.shadow").removeClass('hide');
var tds = $(this).parent().prevAll(); //获取到“编辑”父标签前面的所有标签
tds.each(function(){
var target = $(this).attr('target'); //获取标签target属性的值
var text = $(this).text(); //获取标签的文本内容
$('.modal input[name ="'+ target + '"]').val(text); //将值传给输入框
})
})
</script>
</body>
</html>
使用索引来实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.menu{
height: 40px;
background-color: #eeeeee;
line-height: 40px;
}
.active{
background-color: brown;
}
.menu .item{
float: left;
padding: 0 15px;
border-right: 1px solid red;
cursor: pointer; /*鼠标变小手*/
}
.content{
height: 400px;
border: 1px solid black;
}
.text{
height: 400px;
}
</style>
</head>
<body>
<div style="width:700px; margin: 0 auto;">
<div class="menu">
<div class="item active">菜单一</div>
<div class="item">菜单二</div>
<div class="item">菜单三</div>
</div>
<div class="content">
<div class="text" style="background-color: red;">内容一</div>
<div class="text hide" style="background-color: blue;">内容二</div>
<div class="text hide" style="background-color: darkgreen;">内容三</div>
</div>
</div>
<script src="jquery-1.12.4.js"></script>
<script>
$(".item").click(function(){
$(this).addClass("active").siblings().removeClass("active");
var v = $(this).index(); //获取菜单标签的索引
$(".content").children().eq(v).removeClass("hide").siblings().addClass("hide"); //eq(v)将菜单索引传给对应的内容索引
});
</script>
</body>
</html>