首页 > 解决方案 > 使用 javascript 和 MathJax 将数学公式字符串添加到文档中

问题描述

当按下按钮添加数学公式时,MathJax 语句似乎没有被解释:

const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);

function displayMath() {
    const body = document.body;
    p = document.createElement('p');
    const a = 3, b = 2;
    const c = a + b;
    const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
    p.innerHTML = math;
    body.appendChild(p);
}
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" async
        src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async>
        </script>
    </head>

    <body>
        <p>press the button to display math like this: \(a + b = c\)</p>
        <button id="go" type="button">Go!</button>
        
        <script src="test.js"></script>
    </body>
</html>

1) MathJax 语句可以通过按钮单击等事件添加吗?

2)如果没有,有更好的选择吗?

感谢您的帮助,谢谢 :>

标签: javascripthtmlstringmathjax

解决方案


您需要再次运行 Mathjax 解析器,将动态添加的表达式转换为数学。这是文档。所以,你需要做的是MathJax.Hub.Queue();在你的新表达式上运行方法。您的代码应如下所示:

const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);

function displayMath() {
    const body = document.body;
    p = document.createElement('p');
    const a = 3, b = 2;
    const c = a + b;
    const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
    p.innerHTML = math;
    body.appendChild(p);
    MathJax.Hub.Queue(["Typeset", MathJax.Hub, p]);
}

是工作小提琴


推荐阅读