Using MathJax to add element to the DOM?

2019-07-10 05:23发布

I am trying to dynamically create an element then do some processing on it. I was trying to use MathJax on that newly created element but I can't pull MathJax.Hub.getAllJax on it.

I typed this in the console to test things out: (MathOutput1 is defined in the HTML)

MathJax.HTML.addElement(document.body, "div", {id: "blah"}, ['` `']);
<div id=​"blah">​` `​</div>​
MathJax.Hub.getAllJax("blah");
[]
MathJax.Hub.getAllJax("MathOutput1")
[Object]

Is there a way I can dynamically create an element that I can act on?

I did confirm that the div element blah was added to the dom (at least according to chrome) ""

Thanks :)

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-10 06:03

The problem here is that MathJax operates asynchronously, and you're trying to access the new element before the MathJax.Hub routines are fully finished.

To get around this, you can put your call to MathJax.Hub.getAllJax() in a callback function on the Hub's callback queue:

function showBlahElement () {
    console.log(MathJax.Hub.getAllJax("blah"));
}

MathJax.HTML.addElement(document.body, "div", {id: "blah"}, ['$$a=b$$']);
MathJax.Hub.Queue(showBlahElement);

Or, you can register a signal listener that will get triggered whenever a certain event happens (in this case, whenever new math is typeset):

MathJax.Hub.Register.MessageHook("New Math", function (message) {
  console.log(MathJax.Hub.getAllJax("blah"));
});

MathJax.HTML.addElement(document.body, "div", {id: "blah"}, ['$$a=b$$']);

For more information, see the API docs.

查看更多
登录 后发表回答