我有一个可以在Online Demo查看的MathJax演示。
在这个演示中,我在div中有一些Tex标记,可以通过MathJax完美呈现。
但是,如果我通过单击Add Math Markup
按钮然后单击Rerender Math Markup
按钮以编程方式将一些Tex标记添加到上面的div中,则会导致重复呈现先前呈现的Math标记。这可以在以下视频中看到:Math being rendered repeatedly
单击Rerender Math Markup
按钮时我正在执行的操作是调用以下方法MathJax.Hub.Typset(divElement)
。 divElement是以编程方式添加Tex标记的div。
我的情况的演示代码
<script>
function reRenderMath() {
var div = document.getElementById("mathMarkup");
//render Math for newly added Tex markup
MathJax.Hub.Typeset(div);
}
function addMath() {
var div = document.getElementById("mathMarkup");
div.innerHTML = div.innerHTML + "$$\sin^{-1}.6$$";
document.getElementById("btnRenderMath").disabled = false;
}
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<button type="button" onclick="addMath();return false;" id="btnAddMath" >Add Math Markup</button>
<button type="button" onclick="reRenderMath();return false;" id="btnRenderMath" disabled>Rerender Math Markup</button>
<div id="mathMarkup">
$$x^2 = x +2$$
</div>
重复渲染的屏幕截图
答案 0 :(得分:1)
@Sunil谢谢答案
总结:
所需脚本:
var MathJaxUtils = (function () {
let obj = {};
let scripts = null;
obj.render = function (element) {
scripts = new Array();
$(element).find("script[id^='MathJax-Element']").each(function () {
scripts.push({
displayElement: $(this).prev("div")[0],
scriptElement: this
});
});
//remove all html within MathJax script tags so it doesn't get typset again when Typeset method is called
$(element).find("script[id^='MathJax-Element']").remove();
//render Math using original MathJax API and in callback re-insert the MathJax script elements in their original positions
MathJax.Hub.Queue(["Typeset", MathJax.Hub, element, typeSetDone]);
};
//callback for Typeset method
function typeSetDone() {
for (var i = 0; i < scripts.length; i++) {
$(scripts[i].displayElement).after(scripts[i].scriptElement);
}
//reset scripts variable
scripts = [];
};
return obj;
}());
基本用法:
let elem = document.getElementById("mathContainer");
MathJaxUtils.render(elem);
演示: math-jax-test