前端做假修改(只更改顯示數(shù)據(jù)),實(shí)際更改數(shù)據(jù)(更改數(shù)據(jù)庫(kù))后臺(tái)執(zhí)行。
當(dāng)前代碼段為前端代碼展示: (推薦學(xué)習(xí):前端視頻)
HTML:
test.html
<!DOCTYPE html> <html class="no-js"> <!--<![endif]--> <head> <script src="js/test.js"></script> <style> td { border:solid 1px; width:200px; height:auto; text-align:center; } </style> </head> <body> <table> <tr> <td οnclick="test(this)">test1</td> <td οnclick="test(this)">test2</td> </tr> <tr> <td οnclick="test(this)">test1</td> <td οnclick="test(this)">test2</td> </tr> </table> </body> </html>
JS:
test.js
var firstValue = ""; var nowDom = "";//當(dāng)前操作的td //點(diǎn)擊更改事件 function test(doms) { doms.removeAttribute("onclick"); nowDom = doms; var text = doms.innerText; doms.innerHTML = '<input type="text" value="' + text + '" id="input" οnchange="chane(this)" οnblur="inputOnblur(this)"/>'; firstValue = text; document.getElementById("input").focus(); } //文本框更改事件 function chane(doms) { var text = doms.value; if (text != firstValue) { //提交后臺(tái)更改數(shù)據(jù)庫(kù) //前端操作 nowDom.innerHTML = ""+text; nowDom.setAttribute("onclick", "test(this)"); } } //文本框失焦事件 function inputOnblur(doms) { var text = doms.value; if (text != firstValue) { //提交后臺(tái)更改數(shù)據(jù)庫(kù) } nowDom.innerHTML = "" + text; nowDom.setAttribute("onclick", "test(this)"); }
原理就是點(diǎn)擊時(shí)將文本改成輸入框即可!
效果演示:
點(diǎn)擊文本后效果:
鼠標(biāo)失焦或者回車(chē)保存后效果: