基于contenteditable属性实现在位编辑
HTML5规范引入了contenteditable属性,它几乎可以用在任何元素上,只要添加这一属性 即可变为可编译区域
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>contenteditable</title>
<style>
ul{
list-style: none;
}
li{
clear: both;
}
li>b,li>span{
display: block;
float: left;
width: 100px;
}
li>span{
width: 500px;
margin-left: 20px;
}
li>span[contenteditable=true]:hover{
background-color: #ffc;
}
li>span[contenteditable]:focus{
background-color: #ffa;
border:1px shaded #000;
}
</style>
</head>
<body>
<h1>User information</h1>
<div id="status"></div>
<ul>
<li><b>Name</b>
<span contenteditable="true">Shuai Bi</span>
</li>
<li><b>City</b>
<span contenteditable="true">Anywhere</span>
</li>
<li><b>State</b>
<span contenteditable="true">OH</span>
</li>
<li><b>Postal Code</b>
<span contenteditable="true">10010</span>
</li>
<li><b>Email</b>
<span contenteditable="true">[email protected]</span>
</li>
</ul>
</body>
</html>
现在虽然可以在位编辑但是离开当前页面或者刷新之后,修改数据会丢失 ,借助jQuery实现将修改后的数据提交到后台
实现思路是为每一个contenteditable属性值为true的span标签添加事件监听器 ,具体代码如下:
$(function(){
var status = $("#status");
$("span[contenteditable=true]").blur(function() {
var field = $(this).attr('id');
var value = $(this).text();
$.post('/path/to/file', field+"="+value, function(data) {
status.text(data);
}); });
})