2012-03-27 45 views
0

我想重構某個元素的結構。目前,它大致類似於這種結構。在jQuery中改變這種DOM結構的有效方法

<li> 
    <a class="unitWrapper" href="location_url"> 
     stray textNode 
     <img src="project1.jpg"> 
    </a> 
    <a class="unitWrapper" href="another_url"> 
     link text 
    </a>  
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>      
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> 
</li> 

,我希望它建成使用jQuery以下結構的概括:

  • 獲取列表中的項目
  • 找到的第一個環節展開它從它的內容
  • 用它來包裹列表項中的所有內容
  • 如果鏈接解開包含文本,將它們包裝在<p>

這裏的新結構:

<li> 
    <a href="location_url"> 
     <p>stray textNode</p> 
     <img src="project1.jpg"> 
     <a class="unitWrapper" href="another_url"> 
      link text 
     </a>  
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>      
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> 
    </a> 
</li> 

而且我現在有(這是有點笨重)的jQuery代碼是這樣的:

$('li').find('.unitWrapper').eq(0).each(function() { //get only the first link 
    var $link = $(this); 

    var $wrapperLink = $('<a/>');     //the wrapper link 
    var $strayWrapper = $('<p/>');     //wrapper for stray textNodes like "link text" above 

    $wrapperLink.attr('href', $link.attr('href')); //copy link's location to the wrapper 

    $link.contents()      //get all the link's contents 
     .unwrap()      //unwrap it 
     .parent()      //go to the parent (<li>) 
     .contents()      //get all li's contents 
     .wrapAll($wrapperLink)   //wrap it with the <a> created earlier 
     .filter(function(){       
      return this.nodeType == 3; //get all stray text nodes 
     }) 
     .wrapAll($strayWrapper);   //wrap them with the <p> created earlier 
});​ 

是有沒有這樣做更好的方法?而唯一軸承我已經是<li>和選擇字符串.unitWrapper

回答

1

最簡單的方法似乎是內容的其餘部分元素追加到第一:

$('li').each(function() { 
    var first = $('a.unitWrapper', this).first(); 
    first.removeClass('unitWrapper') 
     .append(first.siblings()) 
     .contents() 
     .filter(function(){       
      return this.nodeType == 3; //get all stray text nodes 
     })   
     .wrapAll("<p/>"); 
}); 

http://jsfiddle.net/infernalbadger/wA3EJ/3/

不能找到一種方法來包裹流浪文本節點比這更容易

+0

完美!我非常專注於解開所有的東西,我從來沒有想過將它附加進去。謝謝! – Joseph 2012-03-27 09:21:34

相關問題