innerHTML 添加脚本导致错误

innerHTML adding scripts causes error

这是我用来为 TeX 添加脚本的函数:

function change() {
        var format = document.getElementById("format");
        var original_text = document.getElementById("question");
        var s = document.createElement('script');
        s.setAttribute('type', 'math/tex; mode=display');
        s.value = {x};
        var newdiv = document.createElement('div');
        newdiv.innerHTML = s.toString();
        document.body.appendChild(newdiv);
    }

但这显示错误 ReferenceError: Can't find variable: change

我哪里错了?

拒绝这条线:

s.value = {x};

方括号用于 JSON (JavaScript Object Notation) Javascript 的对象字面量语法。它期待你以哈希图结束,像这样:

s.value = {x: 'someValue'}

你的右括号出人意料。但是,您实际上 想要的是一个字符串。就 Javascript 而言,字符串对 LaTex 有特殊意义的事实只是巧合:

s.value = '{x}';

这是否能实现您的最终目标还有待观察,但如果没有,那么您可能需要提出一个单独的问题。快乐编码 <3

我猜你可能想做类似的事情:

function change() {
    var format = document.getElementById("format");
    var original_text = document.getElementById("question");
    var s = document.createElement('script');
    s.setAttribute('type', 'math/tex; mode=display');
    s.innerHTML = "{x}";
    var newdiv = document.createElement('div');
    newdiv.appendChild(s);
    document.body.appendChild(newdiv);
}

调用change()函数在<body>标签末尾添加一个div with script标签,如:

<div><script type="math/tex; mode=display">{x}</script></div>

我终于明白我的问题是什么了。这只是我在 html 页面中转换或呈现 MathJax 脚本的错误方式。应该这样固定:

添加另一个脚本:

<script>
  //
  //  Use a closure to hide the local variables from the
  //  global namespace
  //
  (function () {
    var QUEUE = MathJax.Hub.queue;  // shorthand for the queue
    var math = null;                // the element jax for the math output.

    //
    //  Get the element jax when MathJax has produced it.
    //
    QUEUE.Push(function () {
      math = MathJax.Hub.getAllJax("MathOutput")[0];
    });

    //
    //  The onchange event handler that typesets the
    //  math entered by the user
    //
    window.UpdateMath = function (TeX) {
      QUEUE.Push(["Text",math,"\displaystyle{"+TeX+"}"]);
    }
  })();
</script>

那么就可以很方便的转换成这样:

<p>
Type some TeX code: (Example: \int\sin{x}\;{dt})
</p>
<input id="MathInput" class="form-control" type="text" size="50" onchange="UpdateMath(this.value)" />
<p>

<div id="MathOutput">
You typed: ${}$
</div>

输出如下:

感谢@DemoUser 的宝贵回答。