2013-07-14 54 views
1

在頁面上,我需要檢測其中包含圖像的所有條目,並向H1和img添加樣式,並在這些條目中包含img 。到目前爲止沒有問題。從DOM中分離元素,將其插回到不同的位置

<div class="entry"> 
    <h1>Headline</h1> 
    <p><img></p> 
    </div> 

    $("div.entry img").closest(".entry").find("h1").addClass("home-h1-adjust"); 
    $("div.entry img").closest("p").addClass("home-p-img-adjust"); 

完全解決我所面臨的問題,我需要分離無論是H1或P,並重新插入到該p而來的H1之前,這是一系列的條目,並不是所有的其中有一個圖像。

我陷入了正確的方式來循環和prepend jQuery中的分離元素。謝謝。

回答

0

下面是工作的解決方案:遍歷頁面上的所有條目,查找圖像,將類附加到H1和第一個p標籤。作爲入口div的第一個子項,在包含H1的圖像上面加上p。

<div class="entry"> 
    <h1>Headline 1</h1> 
    <p><img />Image? Yes</p> 
    <p>Some Text that needs to stay put</p> 
    <p>More copy text</p> 
    </div> 

    <div class="entry"> 
    <h1>Headline 2</h1> 
    <p>Text in a non image entry</p> 
    <p>This text has no image to keep it company</p> 
    </div> 


    $('div.entry').each(function(){ 
    var $this = $(this); 
    if($this.find('img').length > 0) { 
     $this.find('h1').addClass('home-h1-adjust'); 
     var $img = $this.find('p').first().addClass('home-p-img-adjust'); 
     $this.prepend($img); 
    } 
    }); 

http://jsfiddle.net/lockedown/vkeeD/1/

1
$('.entry > p').each(function() { 
    $(this).insertBefore(this.previousElementSibling); 
}); 

http://jsfiddle.net/Yr96v/

+0

感謝幫助,不確定的。我必須只針對第一個p標籤,並且只能針對帶有圖像的條目。這小提琴顯示我的最終解決方案。 http://jsfiddle.net/lockedown/vkeeD/1/ – lockedown

1
//for each entry 
$('div.entry').each(function(){ 
    var $this = $(this); 

    //if entry has img 
    if($this.find('img').length > 0) { 
     //jQuery is chainable, and detaching is done automatically 
     $this.find('h1').addClass('home-h1-adjust') 
      .before($this.find('p').addClass('home-p-img-adjust')); 
    } 
}); 

http://jsfiddle.net/tB8f4/

+0

這真的幫助我開始。有些條目中有多個p標籤,其他條目只有兩個。小提琴如果你有興趣: http://jsfiddle.net/lockedown/vkeeD/1/ – lockedown

+1

這很酷。我看着你的最終代碼。你可以做到這一點。 [鏈接](http://jsfiddle.net/tB8f4/35/) – joram

+0

啊哈。我以前不知道eq()。這似乎很有用。感謝您花時間分享這些內容,我將來會記住它。 – lockedown

1
$('div.spacer a').addClass('test').each(
    function(){ 
     $(this).remove(); 
    } 
); 

您可以使用.each()只需打開自己的Chrome控制檯和它玩。以上示例將刪除此頁面上的每個相關鏈接。當然你可以這樣做var element = $(this).detach();然後element.appendTo('YOUR POSITION')

+0

謝謝米莎,這是一個偉大的方向,但最終,這個小提琴是我如何解決它。 http://jsfiddle.net/lockedown/vkeeD/1/ – lockedown

相關問題