2013-07-25 41 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()); 
});