使用 javascript 和 MathJax 将数学公式字符串添加到文档

adding math formula string to document using javascript and 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) 如果没有更好的选择?

感谢任何帮助,谢谢 :>

您需要再次 运行 Mathjax 解析器,以将动态添加的表达式转换为数学。这里是documentation。 所以,你需要做的是在你的新表达式上使用 运行 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]);
}

here is working fiddle