如何将HTML表格转换为纯文本并将其保存为JavaScript中的变量

时间:2014-01-23 22:35:22

标签: javascript jquery

我正在查看该网站并找到JavaScript: How to strip HTML tags from string?,但这并没有真正解释如何解决这个问题:

<tr id="element.incident.comments.additional">
<td colspan="2">
<span style="">
<table cellpadding="0" cellspacing="0" style="table-layout:fixed" width="100%">
<tbody>
<tr>
<td colspan="2">
<hr>
</td>
</tr>
<tr style="">
<td class="tdwrap"><strong>2014-01-23 14:45:40 - <a style="color:blue" href="sys_user.do?sysparm_view=itil&amp;sysparm_query=user_name=Superhero@superhero.com">SuperHero</a></strong></td>
<td align="right" nowrap="true"><sup>Additional comments</sup></td></tr>
<tr style="">
<td colspan="2"><span style="word-wrap:break-word;">received from: SDUperhero@superhero.com<br><br>lalalalalala
<br>lotsofwords<br><br><br><br><br><br>
The information transmitted, including any attachments, is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material</span></td></tr></tbody></table></span></td>
</tr>

并获取内部文字:

<tr id="element.incident.comments.additional"> 

进一步解析。

我试过

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

var commentsField = document.getElementById("element.incident.comments.additional").innerHTML;


alert(strip(commentsField));

但我不确定这是否正确,因为我没有收到警报。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

因为你的id中有.,你需要在你的jQuery选择器中转义它们:

$("#txt").val($("#element\\.incident\\.comments\\.additional").html());

这应该有用。

jsFiddle http://jsfiddle.net/hescano/EQ9b3/