问题
I'm building what is basically a mathematic text editor in an HTML file. My goal is to allow the user to display numbers and MathML symbols in a textarea, but completely without the use of a physical keyboard. On the bottom of the page I have a mock keyboard made of buttons with numbers and arithmetic symbols. When the user clicks these buttons, the corresponding number or symbol will then appear inside the textarea. So far, I can get this to work with numbers, but not the MathML symbols. Is there any way to get these symbols to show up inside the textarea?
To make this easier to understand, here's a function called by one of the buttons to insert the number 1 into the textarea:
function insertOne(mctextarea,oneText='1'){
document.getElementById('mctextarea').value += oneText;
}
And here's a function I tried writing to insert a square root sign into the textarea:
function insertSqrt(mctextarea,sqrt=<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mrow><msqrt>x</msqrt></mrow></math>){
document.getElementById('mctextarea').value += sqrt;
}
...which obviously doesn't work, but I don't know where to begin trying to display MathML in the textarea.
Be aware that I've only been using Javascript for about 3 weeks now, so I'm still learning the ropes. :)
回答1:
Ben, I am very new to stackoverflow.com so I can not post a picture of what this code renders. I am using opensource MathJax.js to render mathematical function in HTML. You can find better examples at www.MathJax.org.
PS: I am still learning how to format answers correctly ;)
Code Example:
<!DOCTYPE html>
<html lang="en" >
<head>
<title></title>
<meta charset="UTF-8" />
</head>
<body>
<p>Have you seen MathJax.js at www.mathjax.org</p>
<p>$$
\large
\begin{align*}
& J(\theta) = \dfrac{1}{m} \sum_{i=1}^m Cost((h_
\theta(x^{(i)}),y^{(i)}) \newline
& Cost((h_\theta(x),y) = -log(h_\theta(x)) \; & \text{if y = 1}\newline
& Cost((h_\theta(x),y) = -log(1-h_\theta(x)) \; & \text{if y = 0}\end{align*}
$$
</p>
<script type='text/javascript' src='http://cdn.mathjax.org/mathjax/late/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>
</body>
</html>
回答2:
html/xml tags inside a text area is a no no, see Rendering HTML inside textarea --it's got some good ideas for other methods you could use.
Also, javascript doesn't allow default args like the ones you have above, see Set a default parameter value for a JavaScript function. You'll need to put your xml string inside single quotes as well.
Probably what you'll want to do is have your buttons insert MathJax markup into the textarea. Then you'll have another function that grabs this text, and renders it in a separate div.
So you have the editable textarea, and a preview div that shows the results, much like the textareas on Stack Overflow.
来源:https://stackoverflow.com/questions/12590359/displaying-mathml-symbols-inside-a-textarea