如何提取html并将其添加到数组中

How to extract html and add them to the array?

本文关键字:添加 数组 html 何提取 提取      更新时间:2023-09-26

我有一个关于上次发布的问题

如何从html标记中提取文本

Oriol的回答对我在表结构之间分离html标记有很大帮助。

然而,还有另一个问题。

var project =[''];
$('#htmlData').contents().each(function(){
    if($(this).is('table')){
         //do something with table
         project.push['end of table'];  //this line of codes is the problem....
    }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
}

假设我有html数据,如以下

<em>first part</em> of texts here
    <table>
    ......
    ......
    </table>
<em>second part</em> of texts

我的项目数组最终如下:

 //2 elements
    ('<em>first part</em> of texts here','end of table <em>second part</em> of texts) 

但我想要的结果是

  //3 elements
    ('<em>first part</em> of texts here','end of table','<em>second part</em> of texts) 

如果选择器looptable标记,则end of table是我推送给array的内容。

我该如何做到这一点?谢谢你的帮助!

问题是,在处理完表之后,您没有在数组中创建新位置。project.length-1在这种情况下总是指"表的末尾"位置,所以它只是将下一个"非表"数据与其连接起来。

试试这个:

    var project =[''],
    j = 0;
$('#htmlData').contents().each(function(){
    if($(this).is('table')){
         //do something with table
         project.push('end of table');  //this line of codes is the problem....
         j=project.length;
    }else{
        if (project[j] == undefined) project[j] = "";
        project[j] += (
            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
}
console.log(project);

我相信有一个更干净的方法,但这应该会给你一个想法。