【问题标题】:Convert an HTML string to DOM and then DOM to Formatted Text将 HTML 字符串转换为 DOM,然后将 DOM 转换为格式化文本
【发布时间】:2022-02-11 05:22:29
【问题描述】:

我使用RtfToHtml Converter 将一些文本打印到我的表格单元格中。它转换成功,然后我希望这个转换后的文本(geResult.NotesLong)被格式化:

<td>
    <script>{ setCommentValue(@colIndex, @rowIndex, @totalColCount, '@geResult.NotesLong', '@geResult.Color');}</script>
</td>

此 JavaScript 函数将其转换为 DOM 元素

function setCommentValue(colIndex, rowIndex, assessmentLength, resultValue, color) {

var str2DOMElement = function (html) {
    var frame = document.createElement('iframe');
    frame.style.display = 'none';
    document.body.appendChild(frame);
    frame.contentDocument.open();
    frame.contentDocument.write(html);
    frame.contentDocument.close();
    var el = frame.contentDocument.body.firstChild;
    document.body.removeChild(frame);
    return el;
  }

 var el = str2DOMElement(resultValue);

 //...code to set elementPos...

 $(".test").get(elementPos).appendChild(el);

}

在我的表格中显示如下

<DIV STYLE="text-align:Left;font-family:Segoe UI;font-style:normal;font-weight:normal;font-size:12;color:#000000;"><P STYLE="margin:0 0 0 0;"><SPAN><SPAN>Lee is an attentive listener who tunes into the task at hand  </SPAN></SPAN></P><P /></DIV>

但是我希望它显示为(在上述标签中定义格式)

Lee 是一个细心的倾听者,会密切关注手头的任务

如何格式化此文本,使其按照标签进行格式化,但表格单元格中只显示文本?

【问题讨论】:

    标签: javascript html dom


    【解决方案1】:

    你的代码是这样结束的:

    [...]</P><P /></DIV>
    

    有错误,应该是

    [...]</P></P></DIV>
    

    (第二次关闭p标签错误/位置)

    补充:实际上,第二个结束 p 标记太多了 - 在您发布的代码中只有一个开头 ptag - 删除它。

    【讨论】:

    • 第二个是一个空的

      标签..但即使删除它,文本仍然与标签一起
    【解决方案2】:

    我终于找到了一种从内部提取纯文本的方法(但它仍然缺少格式)

    html 页面

    <td>
        <script>{ setCommentValue(@colIndex, @rowIndex, @totalColCount, '@geResult.NotesLong', '@geResult.Color');}</script>
    </td>
    

    javascript

    function setCommentValue(colIndex, rowIndex, assessmentLength, resultValue, color) {
    
    String.prototype.replaceAll = function (search, replacement) {
        var target = this;
        return target.split(search).join(replacement);
    };
    
    //replace all text special characters
    var replaced = resultValue.replaceAll("&amp;", "&").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&quot;", "\"").replaceAll("&#039;", "\'");
    
    var parser = new DOMParser();    
    var doc = parser.parseFromString(replaced, "text/xml");       
    
    ....
    
    $(".test").get(elementPos).innerHTML = doc.firstChild.textContent;
    
    }
    

    我的文字有特殊字符,例如 > for > 等,所以我手动替换了它们。

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2011-03-07
      • 1970-01-01
      • 2012-08-23
      • 2011-01-12
      • 2011-09-06
      • 2012-12-02
      • 1970-01-01
      相关资源
      最近更新 更多