javascript – 如何在.txt文件中保存Html表数据?

这是我的Html表.

<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email Id</th>
      <th>Phone Number</th>
      <th>Prefered Contact</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>James</td>
      <td>Miles</td>
      <td>james@abcd.com</td>
      <td>9876543210</td>
      <td>email</td>
    </tr>
    <tr>
      <td>John</td>
      <td>Paul</td>
      <td>john@abcd.com</td>
      <td>9638527410</td>
      <td>phone</td>
    </tr>
    <tr>
      <td>Math</td>
      <td>willams</td>
      <td>Math@abcd.com</td>
      <td>99873210456</td>
      <td>phone</td>
    </tr>
  </tbody>
</table>

在此表中有Save Button.

<input type="button" id="txt" value="Save" />

按钮代码

function tabletoJson(table) {
  var data=[];
  var headers=[];
  for (var i=0;
  i < table.rows[0].cells.length;
  i++) {
    headers[i]=table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
  }
  for (var i=1;
  i < table.rows.length;
  i++) {
    var tableRow=table.rows[i];
    var rowData= {}
    ;
    for (var j=0;
    j < tableRow.cells.length;
    j++) {
      rowData[headers[j]]=tableRow.cells[j].innerHTML;
    }
    data.push(rowData);
  }
  return data;
}

单击“保存”按钮时,html表数据将存储在.txt文档中,而不包含< table>,< tr>,< td>.数据存储格式如下格式.

(James,Miles,james@abcd.com,9876543210,email),
(John,Paul,john@abcd.com,9638527410,phone),
(Math,willams,Math@abcd.com,99873210456,phone)

解决方法:

比上述答案稍微清晰的代码适用于任意数量的列

var retContent = [];
var retString = '';
$('tbody tr').each(function (idx, elem)
{
  var elemText = [];
  $(elem).children('td').each(function (childIdx, childElem)
  {
    elemText.push($(childElem).text());
  });
  retContent.push(`(${elemText.join(',')})`);
});
retString = retContent.join(',\r\n');

jsfiddle with the full code

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...