How can I clone, modify, and prepend an element with jQuery?
I want to clone and prepend a div, however I want to change the prepended div name from preConfi to preConfiXX (eg preConfiA1, preConfiB1) on each iteration. What syntax can I use for this?
/* 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-开发者_C百科choice-2" value="T" />
<input type="radio" data-theme="a" name="preConfi" id="radio-choice-3" value="P" />
</div>
I'll take a shot at what I think you want:
$(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/
精彩评论