英文:
Displaying MathJax in innerHTML attribute calling from a function
问题
考虑我现在有的代码:
<!DOCTYPE html>
<html>
<body>
<h1>选择元素</h1>
<p id="text"></p>
</body>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
document.getElementById("text").innerHTML="$$你好$$";
</script>
</html>
这段代码正常运行,会在text
标签中以MathJax格式显示文本"你好"。但是,如果我在这里引入一个函数,比如:
<!DOCTYPE html>
<html>
<body>
<h1>选择元素</h1>
<button onclick="start()">点击</button>
<p id="text"></p>
</body>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
function start(){
document.getElementById("text").innerHTML="$$你好$$";
}
</script>
</html>
点击带有"点击"文字的按钮后,只会在text
标签中显示文本$$你好$$。那么,我该如何更改它?实际上,为什么会发生这种情况?
英文:
Consider the code I have:
<!DOCTYPE html>
<html>
<body>
<h1>The select element</h1>
<p id="text"></p>
</body>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
document.getElementById("text").innerHTML="$$hello$$";
</script>
</html>
It woks fine and shows the text hello in MathJax format in text
id paragraph. But, if I introduce here a function, say:
<!DOCTYPE html>
<html>
<body>
<h1>The select element</h1>
<button onclick="start()">Click</button>
<p id="text"></p>
</body>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
function start(){
document.getElementById("text").innerHTML="$$hello$$";}
</script>
</html>
Clicking the button that has click
written on it, only shows the text $$hello$$ in the text
tag. Now, how do I change it? Actually, why do such thing happen?
答案1
得分: 2
Mathjax不处理DOM更改,因为您在点击事件中插入HTML内容,所以需要通知MathJax DOM已更改,以便它可以查看DOM并呈现数学内容,您需要调用Mathjax的typeset()
函数来执行此操作,如下所示:
function start(){
document.getElementById("text").innerHTML="$$hello$$";
// 调用typeset
MathJax.typeset();
}
typeset()
同步运行,查找DOM中的任何未处理的数学内容,并对该内容进行排版。
英文:
Mathjax doesnot handle DOM changes, since you are inserting HTML content on click event, you need to inform MathJax that DOM has changed so that it can look into the DOM and render the mathematical content, you need to call Mathjax's typeset()
function to do that, like:
..
function start(){
document.getElementById("text").innerHTML="$$hello$$";
// call the typeset
MathJax.typeset();
}
..
typeset()
runs synchronously lookin for any unprocessed math content in the DOM and typesets that content.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论