开发者

JQuery search and copy DIV

I have a div

<div id="s1">s1</div>

Can JQuery check the ID and create a copy 开发者_开发问答of the div BUT with the 1 being changed to the next number?


$("#s1").clone().attr("id", "s2").insertAfter("#s1");


The objective of this code is to create an ever advancing s index that uses a global sIndex variable that increments as each div is cloned. This allows for continual progressing numbers.

If you don't want the contents of the previous div when copying, try clone(false) instead.

var sIndex = 1;

function cloneSDiv() {
    var parent = $("#s" + sIndex);
    var clone = parent.clone();
    sIndex++;
    clone.attr("id", "s" + sIndex).insertAfter(parent);
}

$(document).ready(function() {

    $('.eventSelector').click(function() {
        cloneSDiv();
    });

});


You can use the clone function of jquery.

like this:

var clone = $("#s1").clone(); However, the ID remains the same, But you can obviously change to that to whatever like: clone.attr({"id":"s2"});


Here is a solution without making the index global (which is all you asked for in the question). It acquires and clones the div, checks the id, and increments it to the next one. Wasn't sure how you planned on acquiring the div so if you are doing something else the important stuff is inside the each function.

$("div").each(function() {
    $(this).clone().attr("id", "s" + (parseInt($(this).attr("id").replace("s","")) + 1)).insertAfter("#s1");
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜