关于javascript:使用MathJax设置/渲染动态内容

Typeset/render dynamic content with MathJax

我使用MathJax来显示数学方程式,在静态编写的数学中运行良好。 但不适用于动态添加的数学。

这是我的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<body>
    //Static  
       
            <span>\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)</span>                
         
       //Dynamic
       

         
        <script type="text/javascript" src="js/jquery.js">
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML">

        <script type="text/javascript">
            $(document).ready(function(){
                $('#dynamic-pan').empty();
                $('#dynamic-pan').append('<span>\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)</span>');
            });
       
</body>

我用两个span元素写过数学。 第一个是静态声明的,第二个是动态添加到文档就绪函数中的

请帮助我解决问题。


MathJax v3

http://docs.mathjax.org/en/latest/web/typeset.html

  • 同步排版:MathJax.typeset()
  • 异步排版:MathJax.typesetPromise()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
setTimeout(function () {
  const content = document.createElement('span')
  content.textContent = '\\\\(x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}\\\\)'

  const done = document.createElement('span')
  done.textContent = '   done!'
 
  const syncTypeset = document.querySelector('#syncTypeset')
  syncTypeset.appendChild(content.cloneNode(true))
  setTimeout(function () {
    MathJax.typeset()
    syncTypeset.appendChild(done.cloneNode(true))
  }, 3000)

  const asyncTypeset = document.querySelector('#asyncTypeset')
  asyncTypeset.appendChild(content.cloneNode(true))
  setTimeout(async function () {
    await MathJax.typesetPromise()
    asyncTypeset.appendChild(done.cloneNode(true))
  }, 3000)
}, 0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]
  },
  svg: {
    fontCache: 'global'
  }
};

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" id="MathJax-script">

//Static

  <span>\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)</span>

//Dynamic
Sync after 3 second:
Async after 3 seconds:

MathJax v2

您需要告诉MathJax使用Typeset()方法完成未处理的数学运算,因为MathJax可能在调用Typeset()时正在运行,因此您需要将其添加到队列中

1
2
3
4
5
6
$(document).ready(function() {
  var $el = $('#dynamic-pan')
  $el.empty()
  $el.append('<span>\\\\(x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}\\\\)</span>')
  MathJax.Hub.Queue(['Typeset', MathJax.Hub, $el[0]]);
});
1
2
3
4
5
6
7
8
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML">

//Static

  <span>\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)</span>

//Dynamic

有关更多信息,请参考此文档

编辑:字符\\在字符串上具有特殊含义(转义以下字符),以避免此行为,请确保使用\\\\使其出现在最终字符串中