MathJax is duplicating my equations — why and how can I fix this?

左心房为你撑大大i 提交于 2019-12-04 15:54:28

There are several problems with your approach. The reason that MathJax is reprocessing the whole document is because of how you increment el in the submit() function. You use a post-increment, el++, so that after the line

var d = "<p id='a"+(el++)+"'>"+$out+"</p>";

el is one larger than the ID of the paragraph you are adding. So later when you do

MathJax.Hub.Queue(["Typeset",MathJax.Hub,"a"+el+""]);

the ID that you are passing doesn't refer to the newly added <p> tag, and in fact, there is no such ID. When the ID can't be found, MathJax processes the whole page.

As for the duplication of math, that is because you are using innerHTML to update the output area. Doing that destroys the existing DOM and replaces it with a new one (a very inefficient approach). In doing so, you sever the connection between the MathJax and the existing mathematics in the DOM, so MathJax doesn't know that the math has been processed. So when it reprocesses the page, it tries to typeset the math again (though it only gets as far as creating the preview in this case, but that is the math you see as a duplicate).

It is best not to use innerHTML to replace the contents of an element that contains MathJax output. In addition to disconnecting the output from MathJax, you also lose the event handlers that MathJax uses for things like its contextual menu and zooming functions. It would be better to use explicit DOM manipulation commands like document.createElement() and appendChild(). These take a little more work, but will be much more efficient, especially for longer documents, and will not cause MathJax problems.

MathJax actually provides some support for creating elements this way, so you could take advantage of those rather than doing it all by hand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!