如何将大块的html标记存储到数组中

How to store chunk of html markup into an array?

本文关键字:存储 数组 html      更新时间:2023-09-26

我正在尝试提取用户input html数据并将其存储在objectarray

html的来源可能如下

begin <em>texts</em>
    description texts here
<table>
   <tr><td>cell 1<td><td>cell2</td></tr>
   <tr><td>cell 3<td><td>cel4</td></tr>
</table>
<em>second<em> part texts
<table>
   <tr><td>cell 5<td><td>cell6</td></tr>
   <tr><td>cell 7<td><td>cel8</td></tr>
</table>

我需要能够存储以下东西。

表外的所有文本和表中的单元格数据。他们需要井然有序。

我试过

var data = [];
sourceHtml.contents().each(function(){
    if($(this).is('table')){
          var table = $(this)
          var rows = 'rows:' + $('tr', table).length;
          var column ='column:' + $('td', table).length / $('tr', table).length;
          //i need to get the table columns and rows counts
          data.push(rows)
          data.push(column)
          table.find('td').each(function(){
              data.push($(this).text().trim());
          })
        }else{
          data.push($(this).text().trim());
        }
 })

以上内容只会给我sourceHtml中的所有文本,但会丢失我文本的所有markup。在获取我的数据文本时,是否有维护html标记的方法?非常感谢你的帮助!

使用$(this).html() 而不是$(this).text().trim()

希望这能帮助

使用.html()而不是.text()来获取元素的HTML标记内容,而不是文本节点内容。

http://api.jquery.com/html/