2013-07-25 89 views
3

我試圖讓每一個文字在我的html數據由用戶輸入如何提取從HTML標記文本

html像下面

<em>first part</em> of texts here 

    <table> 
    ...... 
    ...... 
    </table> 

<em>second part</em> of texts 

使用jQuery

project =[]; 

$(htmlData).contents().each(function(){ 
    if($(this).is('table')){ 
     //do something with table 
    }else{ 
     if(this.nodeType === 3) { // Will only select element nodes 
        project.push($(this).text()); 
      }else if(this.nodeType === 1){ 
        project.push(this.outerHTML); 
      } 
     } 
    } 

array最後像

array(0=>'<em>first part</em>', 2=>'of texts here',3=>'<em>second part</em>',4=>'of texts') 

我希望能得到像下面這樣

array(0=>'<em>first part</em>of texts here',1=>'<em>second part</em>of texts'); 

如何做到這一點的陣列?謝謝您的幫助!

+0

是如何數組元素應該被分開。在這個例子中,它說數組應該有一個元素。那麼爲什麼不使用字符串作爲累加器而不是數組。 –

回答

1

DEMOhttp://jsfiddle.net/Cbey9/2/

var project =[]; 

$('#htmlData').contents().each(function(){ 
    if($(this).is('table')){ 
     //do something with table 
    }else{ 
     var txt = (
       this.nodeType === 3 ? $(this).text() : 
       (this.nodeType === 1 ? this.outerHTML : '') 
      ).replace(/\s+/g,' ') // Collapse whitespaces 
      .replace(/^\s/,'') // Remove whitespace at the beginning 
      .replace(/\s$/,''); // Remove whitespace at the end 
     if(txt !== ''){ // Ignore empty 
      project.push(txt); 
     } 
    } 
}); 

我明白壞你的問題。如果你想在表拆分,那麼你可以使用

var project =['']; 

$('#htmlData').contents().each(function(){ 
    if($(this).is('table')){ 
     project.push(''); 
     //do something with table 
    }else{ 
     project[project.length-1] += (
      this.nodeType === 3 ? $(this).text() : 
      (this.nodeType === 1 ? this.outerHTML : '') 
     ); 
    } 
}); 
for(var i=0; i<project.length; ++i){ 
    project[i] = project[i].replace(/\s+/g,' ') // Collapse whitespaces 
    .replace(/^\s/,'') // Remove whitespace at the beginning 
    .replace(/\s$/,''); // Remove whitespace at the end 
} 

DEMOhttp://jsfiddle.net/Cbey9/3/

+0

謝謝,但它不會返回我所需要的。你的提琴有第一部分,文本這裏,秒部分,文本,但我需要第一部分在這裏文本秒部分文本 2個元素,而不是4 +1雖然 – FlyingCat

+0

@FlyingCat的不好意思啊,我以爲我瞭解你的問題,但沒有。那麼,我不明白爲什麼「第一部分這裏的文本」應該在一起。你究竟想在哪裏拆分? – Oriol

+0

我想從

元素拆分html基礎。所以如果我們有文本1 ...
文本 2 ...
texts3 ....我想要「<文本...,文本 2 ...,texts3 ...」對不起,我應該更具體。 – FlyingCat

1

放在希望裏面的文字與一些特定的類跨越(不會改變佈局):

<span class="phrase"><em>first part</em> of texts here</span> 

    <table> 
    ...... 
    ...... 
    </table> 

<span class="phrase"><em>second part</em> of texts</span> 

然後你就可以讓他們:

$('span.phrase').each(function() { 
    project.push($(this).html()); 
});