简体   繁体   English

HTML/JS - 从 Markdown 转换时无法呈现 HTML

[英]HTML/JS - Unable to Render HTML while Converting from Markdown

In this example I'm trying to convert everything in #fileDisplayArea to markdown.在这个例子中,我试图将#fileDisplayArea所有内容都转换为#fileDisplayArea However, the raw HTML within the div is not applied.但是,未应用div的原始 HTML。

    <div id="fileDisplayArea"># Title
    Lorem **ipsum** dolor sit amet, *consectetur adipiscing* elit

    <center>Consectetur libero id faucibus nisl tincidunt eget</center>

    In ornare quam viverra orci sagittis eu.
    </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/10.0.0/markdown-it.min.js"></script>
        <script>
            let md = window.markdownit();
            let txt = document.getElementById('fileDisplayArea').innerHTML;
                document.getElementById('fileDisplayArea').innerHTML = md.render(txt);
        </script>

Running this code properly converts the markdown elements but the raw HTML is not read and instead shows up in the output.运行此代码会正确转换 markdown 元素,但不会读取原始 HTML,而是显示在输出中。 Changing the last instance of innerHTML to innerText provides the following output:innerHTML的最后一个实例更改为innerText提供以下输出:

    <p>Lorem <strong>ipsum</strong> dolor sit amet, 
    <em>consectetur adipiscing</em> elit</p>
    <p>&lt;center&gt;Consectetur libero id faucibus nisl tincidunt eget&lt;/center&gt;</p>
    <p>In ornare quam viverra orci sagittis eu.</p>

This shows that the less/greater than symbols are being escaped.这表明小于/大于符号正在被转义。 How do I prevent this?我如何防止这种情况?

You can either use textContent instead of innerText to skip HTML tags or enclose the node in backticks to show it as a code block, but innerText will always convert brackets.您可以使用textContent而不是innerText来跳过 HTML 标签,或者将节点括在反引号中以将其显示为代码块,但innerText将始终转换括号。 This happens because the library you're using watch for strings and you're trying to convert an HTML node.发生这种情况是因为您正在使用的库监视字符串并且您正在尝试转换 HTML 节点。 Also, there's no native way to center text with Markdown.此外,没有使用 Markdown将文本居中的原生方式

For anyone else who may stumble across this, I managed to find the solution.对于可能偶然发现此问题的任何其他人,我设法找到了解决方案。 Within the documentation for markdown-it, certain options are disabled by default.在 markdown-it 的文档中,某些选项默认是禁用的。 Being able to implement raw HTML is disabled.无法实现原始 HTML。 To fix this, the html flag needs to be enabled.要解决此问题,需要启用 html 标志。 Replace:代替:

    let md = window.markdownit();

with the following:具有以下内容:

    let md = window.markdownit({ 
        html: true, 
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM