<ul>
<li>item x</li>
<li>item y</li>
<li>item z</li>
</ul>
<a href="#">Populate</a>
I want to duplicate开发者_JS百科 (copy and append) all <li>
s when clicked on the 'populate' link. How do I do it?
Thanks
Quick and concise version.
$('a').click(function() {
$('ul').children().clone().appendTo('ul');
})
Of course, you may want to define your 'a' and 'ul' with a class or id in order to be more specific.
EDIT:
To expand on the disclaimer given above, this will be a somewhat fragile solution as it will affect all 'a' and 'ul' elements. This may likely not be what you desire.
Better form is to give your html elements classes or ids, and then attach events to those.
Example:
$('#myPopulateAnchorElement').click(function() {
$('#myExpandableUL').children().clone().appendTo('#myExpandableUL');
});
<ul id='myExpandableUL'>
<li>item x</li>
<li>item y</li>
<li>item z</li>
</ul>
<a href="#" id='myPopulateAnchorElement'>Populate</a>
With thanks to Ed Woodcock for suggesting the inclusion of a preemptive solution.
try this:
$(function(){
$('.anchorClass').click(function(){
var ul = $('.ulClass');
ul.append(ul.html());
});
});
EDIT:
You'll need to change your html to:
<ul class="ulClass">
<li>item x</li>
<li>item y</li>
<li>item z</li>
</ul>
<a class="anchorClass" href="#">Populate</a>
var ul = $('ul');
$('a').click(function(){
ul.children().clone(true).appendTo(ul);
});
You can do something like this:
$('a').click(function(){
$('li').each(function(){
$(this).clone().appendTo('your selector where to put the copy');
})
})
精彩评论