使用 MathJax 排版/渲染动态内容

2024-05-06

我使用 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>

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

请帮我解决这个问题。


数学贾克斯 v3

http://docs.mathjax.org/en/latest/web/typeset.html 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>

数学贾克斯 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>

参考这个文件 https://docs.mathjax.org/en/v1.1-latest/typeset.html了解更多信息

编辑:人物\对字符串有特殊含义(它转义以下字符)以避免这种行为,请确保使用\\让它出现在最终的字符串中

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 MathJax 排版/渲染动态内容 的相关文章