javascript - 使用 javascript 和 MathJax 将数学公式字符串添加到文档中
问题描述
当按下按钮添加数学公式时,MathJax 语句似乎没有被解释:
const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);
function displayMath() {
const body = document.body;
p = document.createElement('p');
const a = 3, b = 2;
const c = a + b;
const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
p.innerHTML = math;
body.appendChild(p);
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<p>press the button to display math like this: \(a + b = c\)</p>
<button id="go" type="button">Go!</button>
<script src="test.js"></script>
</body>
</html>
1) MathJax 语句可以通过按钮单击等事件添加吗?
2)如果没有,有更好的选择吗?
感谢您的帮助,谢谢 :>
解决方案
您需要再次运行 Mathjax 解析器,将动态添加的表达式转换为数学。这是文档。所以,你需要做的是MathJax.Hub.Queue();
在你的新表达式上运行方法。您的代码应如下所示:
const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);
function displayMath() {
const body = document.body;
p = document.createElement('p');
const a = 3, b = 2;
const c = a + b;
const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
p.innerHTML = math;
body.appendChild(p);
MathJax.Hub.Queue(["Typeset", MathJax.Hub, p]);
}
推荐阅读
- python - data.to_excel("output.xlsx") 给出缩进错误
- sql - 如何在 SQL 中生成键和聚合 groupby 函数
- python - 将 int 分解为 sum
- css - 填充自动调整到屏幕尺寸
- django - Django:重定向后发送电子邮件
- c++ - 用于初始化引用的指针引用的值
- php - PHP CURL 不会自动添加 Content-Length 标头
- python - Django:与创建自定义用户相关的问题
- cassandra - SubscribeOn 或 PublishOn 不适用于 ReactiveCassandraCrudRepository
- angular - IdentityServer 4:客户端的授权类型无效:authorization_code