标签:
基于contenteditable属性实现在位编辑
HTML5规范引入了contenteditable属性,它几乎可以用在任何元素上,只要添加这一属性 即可变为可编译区域
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>contenteditable</title> 6 <style> 7 ul{ 8 list-style: none; 9 } 10 li{ 11 clear: both; 12 } 13 li>b,li>span{ 14 display: block; 15 float: left; 16 width: 100px; 17 } 18 li>span{ 19 width: 500px; 20 margin-left: 20px; 21 } 22 li>span[contenteditable=true]:hover{ 23 background-color: #ffc; 24 } 25 li>span[contenteditable]:focus{ 26 background-color: #ffa; 27 border:1px shaded #000; 28 } 29 </style> 30 </head> 31 <body> 32 <h1>User information</h1> 33 <div id="status"></div> 34 <ul> 35 <li><b>Name</b> 36 <span contenteditable="true">Shuai Bi</span> 37 </li> 38 <li><b>City</b> 39 <span contenteditable="true">Anywhere</span> 40 </li> 41 <li><b>State</b> 42 <span contenteditable="true">OH</span> 43 </li> 44 <li><b>Postal Code</b> 45 <span contenteditable="true">10010</span> 46 </li> 47 <li><b>Email</b> 48 <span contenteditable="true">shuaibi@someonecompany.com</span> 49 </li> 50 </ul> 51 </body> 52 </html>
现在虽然可以在位编辑但是离开当前页面或者刷新之后,修改数据会丢失 ,借助jQuery实现将修改后的数据提交到后台
实现思路是为每一个contenteditable属性值为true的span标签添加事件监听器 ,具体代码如下:
1 $(function(){ 2 var status = $("#status"); 3 $("span[contenteditable=true]").blur(function() { 4 var field = $(this).attr(‘id‘); 5 var value = $(this).text(); 6 $.post(‘/path/to/file‘, field+"="+value, function(data) { 7 status.text(data); 8 }); 9 10 }); 11 })
标签:
原文地址:http://www.cnblogs.com/liul0703/p/5689492.html