使用MathJax设置/呈现动态内容

Typeset/render dynamic content with MathJax

本文关键字:动态 MathJax 设置 使用      更新时间:2023-09-26

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

这是我的代码

<body>
    //Static  
        <div>
            <span>'(x = {-b 'pm 'sqrt{b^2-4ac} 'over 2a}')</span>                 
        </div> 
       //Dynamic 
        <div id="dynamic-pan">
        </div> 
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('#dynamic-pan').empty();
                $('#dynamic-pan').append('<span>'(x = {-b 'pm 'sqrt{b^2-4ac} 'over 2a}')</span>');
            });
        </script>
</body>

我已经用两个跨度元素写了数学。第一个是静态声明的,第二个是在文档准备功能中动态添加的

请帮我解决这个问题。

MathJax v3

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

  • 同步类型集:MathJax.typeset()
  • 异步类型集:MathJax.typesetPromise()

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)
<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['''(', ''')']]
  },
  svg: {
    fontCache: 'global'
  }
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" id="MathJax-script"></script>
//Static
<div>
  <span>'(x = {-b 'pm 'sqrt{b^2-4ac} 'over 2a}')</span> 
</div>
//Dynamic
<div id="syncTypeset">Sync after 3 second: </div>
<div id="asyncTypeset">Async after 3 seconds: </div>

MathJax v2

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

$(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]]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"></script>
//Static
<div>
  <span>'(x = {-b 'pm 'sqrt{b^2-4ac} 'over 2a}')</span> 
</div>
//Dynamic
<div id="dynamic-pan"></div>

有关的更多信息,请参阅本文档

编辑:字符'在字符串上有特殊含义(它转义了下面的字符)以避免这种行为。请确保使用''使其出现在最后的字符串