<!doctype html> <html> <head> <meta charset="utf-8"> <title>JQuery動態添加控件並取值-jq22.com</title> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <style> </style> </head> <body> <input type="button" onclick="add()" value="增加"> <input type="button" onclick="query()" value="查看"> <ul> <li><span>A:</span> <input type="checkbox"> <input type="text"> <input type="button" class="del" value="刪除"> </li> <li><span>B:</span> <input type="checkbox"> <input type="text"> <input type="button" class="del" value="刪除"> </li> <li><span>C:</span> <input type="checkbox"> <input type="text"> <input type="button" class="del" value="刪除"> </li> <li><span>D:</span> <input type="checkbox"> <input type="text"> <input type="button" class="del" value="刪除"> </li> </ul><script> $(document).ready(function() { init(); }); //初始4個選項 var num = 4; //添加選項 function add() { // alert(num) //添加一行,num加一 num++; //通過知道當前有的按鈕數算出選項名 var str = String.fromCharCode(64 + num); //編輯新選項的html代碼 var $li = $("<li>" + "<span>" + str + ":</span> " + " <input type=\"checkbox\"/>" + " <input type=\"text\" class=\"str\"/>" + " <input type=\"button\" class=\"del\" value=\"刪除\"/></li>"); //將新的一行添加到<ul>中 var $parent = $("ul"); $parent.append($li); //因為添加了新的選項需要重新綁定按鈕 init(); } function query() { // alert(num) var str = ""; var str1 = ""; //for循環查詢已有控件的輸入值 for (var i = 0; i < num; i++) { var a = $("ul li:eq(" + i + ") :text").val(); var b = $("ul li:eq(" + i + ") :checkbox").is(':checked'); var j = i + 1; str += "第" + j + "個文本框輸入:" + a; str1 += "第" + j + "個復選框選中:" + b; } alert(str); alert(str1); } //綁定每個ul li下的刪除按鈕 function init() { //這里其實用ul li input :button就可以,但是給按鈕加一個class方便用css給按鈕添加樣式,這里本人比較懶沒有添加樣式。 $("ul li input.del").unbind("click").click(function() { //$(this).parent().remove();鏈式操作,$(this)為該按鈕本事,parent()為其父元素即<li>,調用renmove()將整個<li>節點刪除 $(this).parent().remove(); //alert(num) //for循環刷新列表,因為考試往往用ABC,所以利用ascii碼通過獲取當前控件的索引來轉換成對應的英文字母, for (var i = 0; i < num - 1; i++) { //ascii碼65對應的A,65加上當前索引值再轉成字符即可 var str = String.fromCharCode(65 + i) + ":"; //定位到每個<li>下的<span>節點,將選項號刷新到頁面 $("ul li:eq(" + i + ") span").html(str); } //刪除一行,num減一 num--; }); }</script> </body> </html>