【问题标题】:How to write Mathjax formulas inside JSON and put into HTML?如何在 JSON 中编写 Mathjax 公式并放入 HTML?
【发布时间】:2021-06-18 07:32:27
【问题描述】:

我的 JSON 文件包含一个 Mathjax 公式:

Mathjax 公式显示不正确,它在编写时显示。当我将该公式直接放入 HTML 时,它可以正常工作,并按应有的方式显示公式。我该怎么办?提前致谢。

const currentQuestion = {
  "question": "\\[x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}.\\]",
  "choice1": "kw",
  "choice2": "k22",
  "choice3": "k3",
  "answer": 3
}

const choices = document.querySelectorAll(".choice-text");

choices.forEach((choice) => {
  const number = choice.dataset['number'];
  choice.innerHTML = currentQuestion['choice' + number];
});
<h2 id="question">Koji je odgovor na sledeca pitanja</h2>
<div class="choice-container">
  <p class="choice-prefix">A</p>
  <p class="choice-text" data-number="1">Choice 1</p>
</div>
<div class="choice-container">
  <p class="choice-prefix">B</p>
  <p class="choice-text" data-number="2">Choice 2</p>
</div>
<div class="choice-container">
  <p class="choice-prefix">C</p>
  <p class="choice-text" data-number="3">Choice 3</p>
</div>

【问题讨论】:

  • 我给你做了一个sn-p。请添加相关的 HTML 和其他代码。例如,您在哪里设置问题?
  • 好的,谢谢,我会添加整个代码。
  • 查看我的更新答案。您需要正确的文件

标签: javascript html json mathjax


【解决方案1】:

这对我有用。忽略 localStorage 警告

我从manual得到了数学脚本文件的url

注意:JSON 需要转义反斜杠:

const questions = JSON.parse(`[{"question":"\\\\[x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}.\\\\]","choices":["kw","k22","k3"],"answer":2},{"question":"\\\\[x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}.\\\\]","choices":["kw","k22","k3"],"answer":2},{"question":"\\\\[x = {-b \\\\pm \\\\sqrt{b^2-4ac} \\\\over 2a}.\\\\]","choices":["kw","k22","k3"],"answer":2}]`)

const letters  = "ABCDEF";
const html = questions.map((question,i) => {
  const choices = question.choices.map((choice,i) => `<p class="choice-prefix">${letters[i]}</p>
  <p class="choice-text" data-number="${(i+1)}">${choice}</p>`).join("");
  return `<h3>${question.question}</h3><div class="choice-container">${choices}</div>`
}).join("")

document.getElementById("questions").innerHTML = html;

console.log(JSON.stringify(questions))
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<h2>Koji je odgovor na sledeca pitanja</h2>
<div  id="questions"></div>

【讨论】:

  • 是的,代码直接在 HTML 中时有效,但我需要的是在 JSON 文件中,因为,我有很多问题,这只是一个例子。所以这应该在 JSON 中并正确显示: "question": "\[x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}.\]", "choice1" :“kw”、“choice2”:“k22”、“choice3”:“k3”、“answer”:3
  • 我不明白。我使用您的 JSON 创建的对象并将代码插入到 html 元素中。您对此有何期望?
  • 问题在于,不知何故,公式不会作为公式而是作为纯文本从 JSON 传输到 HTML。
  • 那是另一回事。您需要正确转义 JSON。查看我从 JSON 实体解析的更新
  • 由于某种原因,当我转义反斜杠时,它只显示公式文本,而不是公式本身。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 2018-07-24
  • 1970-01-01
相关资源
最近更新 更多