2017-02-14 129 views
0

只有在父和子之間沒有文本時,我需要將所有子內聯樣式傳遞給父級。嵌套標籤跨度

<span style="text from style"> <!-- this don't recive the childs' style because there are "cccc" --> 
     cccc 
     <span style="text from style"> <!-- this span recive the style of his child because there aren't plain text between them --> 
      <span style="text from style"> 
      bbb 
      </span> 
     </span> 
</span> 

我得到過孩子樣式父,但我不能檢查的標籤孩子

前後也有文字,這是我的腳本:

currentElement.find('span').each(function(){ 
         var $padreSpan = jQuery(this); //get the parent span 
         jQuery(this).find('span').each(function(){ //pass by all span child 
          var styleChildren = jQuery(this).attr('style'); //get them style 
          $padreSpan.attr('style', $padreSpan.attr('style')+ ";" + styleChildren+";"); //set style child to parent 
         }); 
         $padreSpan.html(
           $padreSpan.html().replace(/<span\b[^>]*>/gi,"").replace(/<\/span>/gi,"") 
         ); //clear child spans 
        }); 

我怎麼能做?

回答

0
var parent=$('span');  
var children=$(parent).children(); 

如果刪除所有子節點,剩下的就是文本。因此:

var backup=$(children).remove(); 
var text=$(parent).text().trim(); 
var length=text.length; 
if(length>0){ 
//it means there is some text here. 
//all the removed node are there in the backup 
//re insert it anyway you like* 
}