自動序列編號和自動屬性編號,效果圖如下:
實現原理:
添加和刪除是逆向過程,實現是一致的。
增加時,向父容器中增加元素append方法,並將所有的自訂屬性編號和序列編號設定為空白,然後通過$.each方法,重新為自訂屬性編號和序列編號賦值。
複製代碼 代碼如下:
$.each(items, function (k, v) {
$(this).attr("opt", "mopt" + k);
serials.eq(k).html(k);
});
刪除時,為所有刪除按鈕綁定事件live方法,將元素從父容器中刪除detach方法,並將所有的自訂屬性編號和序列編號設定為空白,然後通過$.each方法,重新為自訂屬性編號和序列編號賦值。
複製代碼 代碼如下:
$("#test .del").live("click", function () { //為刪除按鈕綁定點擊事件
var dels = test.find(".del"); //所有所刪除按鈕
var delnum = dels.index($(this)); //當前刪除按鈕的索引值
var items = test.find(".item");
items.eq(delnum).detach(); //從父容器中將此節點刪除
items.attr("opt", "");
var serials = test.find(".serial");
serials.html("");
$.each(items, function (k, v) { //自訂屬性重新和編號賦值
$(this).attr("opt", "mopt" + k);
serials.eq(k).html(k);
});
});
樣本如下:
<!DOCTYPE html> <html> <head> <title>each和live實現自動編號</title> <script type="text/javascript" src="http://demo.jb51.net/jslib/jquery/jquery.js"></script> <style type="text/css"> *{margin: 0px;padding: 0px;} .cont{width:600px; margin:60px auto 0px;} #test .item{padding: 10px 6px;border-bottom: 1px solid #666666;} #test .serial{margin-right: 20px;} #test .del{padding: 6px;margin-left: 30px;} </style> </head> <body> <div class="cont"> <input id="btn" type="button" value="增加" /> <div id="test"></div> </div> <script type="text/javascript"> $(function () { var num = 1; var test = $("#test"); $("#btn").click(function () { test.append("<div class='item'><span class='serial'></span>aaaaa" + num + "刪除</div>"); var items = test.find(".item"); var serials = test.find(".serial"); items.attr("opt", ""); serials.html(""); $.each(items, function (k, v) { $(this).attr("opt", "mopt" + k); serials.eq(k).html(k); }); num++; }); $("#test .del").live("click", function () { var dels = test.find(".del"); var delnum = dels.index($(this)); var items = test.find(".item"); items.eq(delnum).detach(); items.attr("opt", ""); var serials = test.find(".serial"); serials.html(""); $.each(items, function (k, v) { $(this).attr("opt", "mopt" + k); serials.eq(k).html(k); }); }); }); </script> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]