Increase element ID by one after every click?

I am trying to clone multiple divs on my page by using the jQuery .clone() method. The problem is, as soon as a div is cloned, it needs to have a unique ID. The cloned ID has to be there too. I was thinking I could keep the old ID and then just add a number on, increasing as more div's are on the page.

Example: base ID = one, so div one would be id, then div two would be id-2, then div three would be id-3, etc.

Is this possible? My attempt at this is below:

$("a").click(function(){
        var target = $(this).attr("href");
        var id = $(target).attr("id");
        $(target).clone().attr("id",id + $(id).size()).attr("class","drag").appendTo("body");
});

Each a tag looks like this:

<a href="#one">One</a>
<a href="#two">Two</a>

Then the cloned element looks like this:

<div class="drag base" style="background-color:blue" id="one"></div>
<div class="drag base" style="background-color:green" id="two"></div>

Answers


See this: http://jsfiddle.net/3tu7V/1/

$(function(){
    $("a").click(function(){
            var target = $(this).attr("href");
            var id = $(target).attr("id"); 
            var click = $(target).data("clicked") || 0;
            $(target).data("clicked", ++click);            
            $(target).clone().attr("id",id + click).attr("class","drag").appendTo("body");

    });
});
‚Äč

I think this does what you want according to your comment: "Ah, is there any way for the element ID to be reset when the base ID is unique? Ex.) "If you clone div "one", it will produce "one-1", then "one-2", but if you then clone div "two", it will produce "two-3", not "two-1""


Need Your Help

Scala support in a maven project

scala maven

I've found a guide to add scala support to a maven project in this link -> http://stuq.nl/weblog/2008-11-26/4-steps-to-add-scala-to-your-maven-java-projects

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.