使用 MathJax 获取 MathML 代码

Get MathML code with MathJax

我构建了一个表单来编写 LaTeX 表达式并使用 MathJax 呈现它们。为了加速MathML代码的复制,我写了一个脚本,在另一个textarea中显示MathML代码,如你can see here

这是我的代码:

<!doctype html>
<html>
<head>
<title>LaTeX para Word</title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  showProcessingMessages: false,
  tex2jax: {
    inlineMath: [
      ['$','$'],
      [ '\(', '\)' ]
    ]
  },
  extensions: ['toMathML.js']
});

var math = null;
MathJax.Hub.queue.Push(function () {
  math = MathJax.Hub.getAllJax('MathOutput') [0];
});

window.UpdateMath = function (TeX) {
  MathJax.Hub.queue.Push(['Text', math, '\displaystyle{' + TeX + '}']);
  document.getElementById('output').value = '<?xml version="1.0"?>' + math.root.toMathML("");
};

function selectTextarea(element) {
  var text = document.getElementById(element).select();
}
</script>
<script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&locale=pt-br"></script>
</head>
<body>

<textarea id="MathInput" cols="60" rows="10" onkeyup="UpdateMath(this.value)"></textarea>

<div id="MathOutput">
$${}$$
</div>
<hr>
<br>
<textarea id="output" cols="60" rows="10" readonly="readonly"></textarea>
<br>
<button onclick="selectTextarea('output')">Selecionar código</button>
<script src="main.js"></script>
</body>
</html>

问题是当我更快地键入公式时,最后一个字符没有显示在 MathML 代码中。有时,我必须在公式末尾添加 space 以获得正确的 MathML 代码。谁能给我一些提示来解决这个问题?

问题是您将 asynchronous 调用与 synchronous 调用混在一起。 Queue 工作 asynchronously,所以当你调用它时:

MathJax.Hub.queue.Push(['Text', math, '\displaystyle{' + TeX + '}']);

不等到实际渲染完成才转到下一行。所以这个调用在完成之前被执行:

document.getElementById('output').value = '<?xml version="1.0"?>' + math.root.toMathML("");

解决它的一种方法是将输出更新也加入队列,您可以通过创建另一个函数来处理输出并在渲染后将其排队,这样它只会在渲染时执行做完了。例如:

window.updateMathMl = function (math) {
    document.getElementById('output').value = '<?xml version="1.0"?>' + math.root.toMathML("");
};

window.UpdateMath = function (TeX) {
    MathJax.Hub.queue.Push(['Text', math, '\displaystyle{' + TeX + '}'], [updateMathMl, math]);
};

https://jsfiddle.net/ew6vsqy8/1/