2015-09-13 210 views
1

克隆元素我有這樣的代碼:於母公司

<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
  • 更改divul
  • 包裝所有ali
  • 添加類.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); 
}); 
+0

現在的解決方案看起來不錯,什麼問題呢? – dreamweiver

回答

1

當你寫一些邏輯,確保你的方式別人寫它可以很容易地理解你的代碼。

下面是我的解決方案很簡單,但可能需要一些調整,你可能會這樣做。

JS代碼:

$(function() { 
$('.child:eq(0)').addClass('hidden-xs'); 
$('#clone').on('click', function() { 
    var clo = $('.child:eq(0)').clone(); 
    clo.removeClass('hidden-xs'); 
    clo.addClass('show-xs'); 
    var subElements = clo.find('a'); 
    var $newElement = $('<a/>'); 

    subElements.each(function() { 
     var $liEle = $('<li/>'); 
     var $newElement = $('<a/>'); 
     $newElement.html($(this).html()); 
     $newElement.attr('href', $(this).attr('href')); 
     clo.append($liEle.append($newElement)); 
     $(this).remove(); 
    }); 

    $('.parent').append(clo); 
    alert($('.parent').html()); 
}); 
}); 

Live Demo @ JSFiddle

+0

什麼是不明確的部分?對不起,任何不好的描述:/我不想複製它點擊,我想在頁面加載時做到這一點。 – Zoker

+0

嘿,你在單個語句中混雜了太多東西,反正點擊處理器與解決方案無關,它只是一個原型。您可以參考點擊處理程序中的邏輯。 – dreamweiver