克隆元素我有這樣的代碼:於母公司
<div class="parent copy">
<div class="child">
<a href="#">Text</a>
<a href="#">Text2</a>
</div>
</div>
,我想有這樣的輸出:
<div class="parent copy">
<div class="child hidden-xs">
<a href="#">Text</a>
<a href="#">Text2</a>
</div>
<ul class="child show-xs">
<li><a href="#">Text</a></li>
<li><a href="#">Text2</a></li>
</ul>
</div>
- 所以我想複製的
.child
類 - 添加類到主要元素(
.hidden-xs
) - 更改
div
到ul
- 包裝所有
a
與li
- 添加類
.show-xs
的重複元素
我要爲與.copy
類網頁上的每個元素做到這一點。
基本上我知道如何自己做所有這些東西,我的問題是,克隆孩子,使其更有效。 我想是這樣的:
$('.copy .child').clone();
// Problem: How can I append it to the .copy element? .clone().appendTo($(this).parent()); does not work
$('.copy .child:nth-child(1)').addClass('hidden-xs');
$('.copy .child:nth-child(2)').replaceWith($('<ul class="child show-xs>' + this.innerHTML + '</ul>'));
$('.copy .child:nth-child(2) a').wrap('<li></li>');
有沒有辦法讓這個更有效,更容易嗎?
編輯:這是一個基於dreamweiver`s我自己的解決方案:
$(function() {
$('.parent .child').addClass('hidden-xs');
$clone = $('.parent .child').clone();
$clone.removeClass('hidden-xs').addClass('show-xs').wrapInner('<ul class="child show-xs"></ul>');
$clinks = $clone.find('a');
$clinks.each(function() {
$(this).wrap('<li></li>');
});
$('.parent').append($clone);
});
現在的解決方案看起來不錯,什麼問題呢? – dreamweiver