简体   繁体   中英

how to clone an element with specific number of times

what's the syntax to clone an element with assigned times like 5 times? For example, in the html I have this element

<div name="test">
     this is a test
</div>

and I have this clone button which will copy the element once very time I hit it. Then the problem is how can I like just want to copy it 5 times which means after the fifth time I click the copy button, I won't be able to copy the element and get an alart like "already excess maximum "? Thanks in advance!

JS Fiddle
http://jsfiddle.net/DXcQQ/22/

HTML

<div id="content">
    <div name="test" id="item_0">
         this is a test
    </div>
</div>
<button id="btn">Click Me</button>

JS

var maxRows = 5;
var i = 1;

$("#btn").click(function() {     
    if(i < maxRows) {
        $('#item_0').clone().attr("id","item_" + i++).appendTo('#content');
    } else {
        alert('Max Rows Reached!')   
    }
});

Ummm...

.clone()

... and keep a counter on the number of times you call .clone() . Its very simple.

Example:

var counter = 0;

function clonestuff(){
   if(counter < 5) {
      $(stuff).clone()...
      counter ++;
   } else {
      alert('sorry, excessive cloning detected!');
   }
}

http://api.jquery.com/clone/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM