I want to display formulas with MathJax and edit them with CKEditor's Mathematical Formulas. However when I switch from edit mode to display mode the formulas appear blank (being initially and in the edit mode displayed properly). I've been able to reduce it to a small jsfiddle:

JSFiddle

Steps to reproduce it:

  1. Enter the JSFiddle. See how the formula is properly displayed.
  2. Click on the Edit button and somewhere in the text. You will be able to edit the formula in TeX and the surrounding text. Note: I'm using for the jsfiddle a CDN without the Mathematical Formulas plugin, however it doesn't affect the behaviour.
  3. Click anywhere blank in the display rectangle to hide the CKEditor instance.
  4. Now you can click the Save button. As you can see, the formula is not displayed anymore.

However if you inspect the element you'll see how the initial code in the step 1 and the one after this step is the same but now it's not shown.

The HTML code:

<div id = "fullarticle" contenteditable = "false">
    <p>Some text</p>
    <span class = "math-tex">
        \(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)
    </span>
    <p>Some more text</p>
</div>
<button class = "edit">Edit</button>
<button class = "save">Save</button>

The javascript code:

$(".edit").click(function(){
  $(".math-tex").each(function(index){
    $(this).html("\\(" + $(this).find("script").html() + "\\)");
    });
  $("#fullarticle").attr("contenteditable", "true");
  CKEDITOR.inline('fullarticle');
  });

$(".save").click(function(){
  var mytext = CKEDITOR.instances.fullarticle.getData();
  $("#fullarticle").html(mytext).attr("contenteditable", "false");
  MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
  for(k in CKEDITOR.instances) {
    var instance = CKEDITOR.instances[k];
    instance.destroy();
    }
  });

Edit:

After some testing, I can confirm it has to do to the fact that I'm mixing CKEditor and MathJax, since in this fiddle the issue cannot be seen.

有帮助吗?

解决方案

I got it working. Apparently is some kind of timing/order issue:

JSFiddle

The new Javascript:

$(".edit").click(function(){
  $(".math-tex").each(function(index){
    $(this).html("\\(" + $(this).find("script").html() + "\\)");
    });
  $("#fullarticle").attr("contenteditable", "true");
  CKEDITOR.inline('fullarticle');
  });

$(".save").click(function(){
  $("#fullarticle").attr("contenteditable", "false");

  for(k in CKEDITOR.instances) {
    var instance = CKEDITOR.instances[k];
    instance.destroy();
    }

  MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
  });

However, you cannot edit/save multiple times. Try it, the second consecutive time that you press edit it will display really bad.

其他提示

Did you see the Mathjax plugin? You can see demo a here. As you'll find out, embedding such thing as MathJax inside contenteditable is very tricky, therefore I do not recommend trying to implement it by yourself.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top