简体   繁体   中英

How to add a mathjax equation into the html page using a javascript button

Say I wanted to generate a random fraction on a webpage using MathJax, I might write this:

function newFrac() {
    a1 = ran(1,20);
    a2 = ran(1,20);
    var txt = "$ \frac{"+a1+"}{"+a2+"} $"
    document.getElementById("a").innerHTML=txt;
}

where ran(1,20) calls a function to generate a random number. Then when the user clicked the button to make a new fraction it would write, say, $ \\frac{3}{7} $ on my webpage, but I don't want that, I want the equation displayed. How would I do that? How would I tell it to update after the javascript had changed the html?

To evaluate math on the page after MathJax has processed it, you need to queue a call to Typeset via MathJax.Hub.Queue(["Typeset", MathJax.Hub, el]) where el is the element containing the math that needs to be evaluated:

function newFrac() {
    a1 = ran(1,20);
    a2 = ran(1,20);
    var txt = "$ \frac{"+a1+"}{"+a2+"} $"
    var el = document.getElementById("a");
    el.innerHTML=txt;
    MathJax.Hub.Queue(["Typeset", MathJax.Hub, el]);
}

See Modifying Math on the Page for more detail. See the section on Manipulating Individual Math Elements if you want to change an existing equation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM