如何使用jQuery克隆,修改和添加元素?

时间:2011-07-10 20:22:31

标签: jquery clone prepend

我想克隆并添加div,但是我想更改前面的div名称 从每个迭代的preConfi到preConfiXX(例如preConfiA1,preConfiB1)。我可以使用什么语法?

/* on initial load,  move default template into each GroupX location */
var groups = ['A','B','C','D','E','F','G']
for (var groupLetter in groups){
    $('#template').clone().prependTo('#placeholder' + groups[groupLetter]);
}


        <!-- ************************** --> 
    <!-- *******  GROUPS   ******** --> 
    <!-- ************************** --> 
    <div id='groupA' class='preGroups'> 
    GroupA
    <div id="placeholderA"></div>
    </div>

    <div id='groupB' class='preGroups'> 
    GroupB
    <div id="placeholderB"></div>   
    </div>

         ....

    <div id='groupF' class='preGroups'> 
    <div id="placeholderF"></div>
    GroupF
    </div>


<div id='template'> 
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-1" value="C" /> 
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-2" value="T" /> 
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-3" value="P" /> 
</div> 

1 个答案:

答案 0 :(得分:6)

我会拍摄我认为你想要的东西:

$(document).ready(function() {
    var groups = ['A','B','C','D','E','F','G'];
    for (var groupLetter in groups){
        var myClone = $('#template').clone();
        myClone.attr("id", "template-"+groups[groupLetter]);

        var index = 1;
        myClone.find("input[type^=radio]").each(function() {
            var myName = $(this).attr("name");
            $(this).attr("name", myName+groups[groupLetter]+index++);
        });

        myClone.prependTo('#placeholder' + groups[groupLetter]);
    }
});

http://jsfiddle.net/a5HB7/3/