軟件開發實際就是數據的增刪改查,javascript前端開發也不例外。今天學了jquery框架的簡單使用。于是用它實現簡單的增刪改,接著也用原始的javascript實現同樣的功能,以便看出jquery的強大:
代碼如下:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title><script type="text/javascript" src="jq/jquery-1.9.1.js"></script><script type="text/javascript">$(function(){gaoliang();var $seldel = undefined;var seldel = undefined;//高亮選中function gaoliang() {$("li").click(function () {$("li").css("backgroundColor", "red");this.style.backgroundColor = "yellow";$seldel = $(this);seldel = this;});}//使用jquery添加對象$("#btnAdd1").click(function () {var input = window.prompt("輸入數據");var $newli = $("<li>" + input + "</li>");$newli.appendTo("#Ol");gaoliang();});//使用dom元素添加對象document.getElementById("btnAdd2").onclick = function () {var input = window.prompt("輸入數據");var newli = document.createElement("li");newli.innerHTML = input;document.getElementById("Ol").appendChild(newli);gaoliang();}//使用jquery刪除對象$("#btnDel1").click(function () {$seldel.remove();});//使用dom元素刪除對象document.getElementById("btnDel2").onclick = function () {seldel.parentNode.removeChild(seldel);}//使用jquery插入數據$("#btnInsert1").click(function () {var input=window.prompt("輸入插入的數據");var $newli=$("<li>"+ input+"</li>");$newli.insertBefore($seldel);gaoliang();});//使用dom插入數據document.getElementById("btnInsert2").onclick = function () {var Ol = document.getElementById("Ol");var input = window.prompt("輸入插入的數據");var newli = document.createElement("li");newli.innerHTML = input;Ol.insertBefore(newli, seldel);gaoliang();}//使用jquery編輯選中的數據$("#btnEdit1").click(function () {var oldtxt = $seldel.html();var $edit = $("<input id='btnE' type='text' value='" + oldtxt + "'/>");$seldel.html($edit);$edit.focus();$edit.blur(function () {var newtxt = $(this).val();$seldel.html(newtxt);});});//使用dom編輯選中的數據document.getElementById("btnEdit2").onclick = function () {var edittext = document.createElement("input");edittext.type = "text";edittext.value = seldel.innerHTML;;seldel.innerHTML = "";seldel.appendChild(edittext);edittext.focus();edittext.onblur = function () {seldel.innerHTML = edittext.value;}}} )</script></head><body><ol id="Ol"><li id="haha">1</li><li>2</li><li>3</li><li>4</li></ol><input id="btnAdd1" type="button" value="jquery添加數據" /><input id="btnAdd2" type="button" value="dom添加數據" /><input id="btnDel1" type="button" value="jquery刪除數據" /><input id="btnDel2" type="button" value="dom刪除數據" /><input id="btnInsert1" type="button" value="jquery插入數據" /><input id="btnInsert2" type="button" value="dom插入數據" /><input id="btnEdit1" type="button" value="jquery編輯數據" /><input id="btnEdit2" type="button" value="dom編輯數據" /></body></html>
新聞熱點
疑難解答