4

I am trying to get every texts in my html data which is input by the user

I have html like the following

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

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

<em>second part</em> of texts

I use 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);
            }
         }
     }

the array ends up like

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

I was hoping to get an array like the following

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

How do I accomplish this? Thanks for the help!

4

2 回答 2

1

将您想要的文本放在具有某些特定类的 span 中(不会改变布局):

<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());
});
于 2013-07-25T01:18:32.667 回答
1

演示:http: //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
}

演示:http: //jsfiddle.net/Cbey9/3/

于 2013-07-25T00:46:15.727 回答