Automatic sequence numbering and automatic property numbering, the effect is shown below:
Implementation principle:
Adding and deleting is the reverse process and the implementation is consistent.
When added, adds an element append method to the parent container, sets all custom attribute numbers and sequence numbers to NULL, and then assigns values to the custom attribute number and sequence number by $.each method.
Copy Code code as follows:
$.each (items, function (k, v) {
$ (this). attr ("opt", "mopt" + K);
Serials.eq (k). html (k);
});
When deleted, bind the event live method for all delete buttons, remove the Detach method from the parent container, and set all custom attribute numbers and serial numbers to NULL, and then assign values to the custom attribute number and sequence number by $.each method.
Copy Code code as follows:
$ ("#test. Del"). Live ("Click", Function () {//To bind the Delete button to a point-click event
var dels = Test.find (". del"); All the deleted buttons
var delnum = Dels.index ($ (this)); Index value of the current Delete button
var items = Test.find (". Item");
Items.eq (Delnum). Detach (); Remove this node from the parent container
Items.attr ("opt", "");
var serials = Test.find (". Serial");
Serials.html ("");
$.each (items, function (k, v) {//custom attribute re and number assignment
$ (this). attr ("opt", "mopt" + K);
Serials.eq (k). html (k);
});
});
Examples are as follows:
<! DOCTYPE html> <ptml> <pead> <title>each and live implementation automatic numbering </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> </pead> <body> <div class= "cont" > <input id= "btn" type= "button" value= "Add"/> <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 + "Delete </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> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]