为什么 Javascript 代码在尝试保存 ACE 编辑器的内容时会运行

Why Javascript code gets running while trying to save ACE editor's content

本文关键字:运行 编辑器 ACE 代码 Javascript 保存 为什么      更新时间:2023-09-26

我正在尝试保存ace编辑器的内容,其中包含一些JavaScript示例代码,如下所示:

<script>
  (function(){
     alert("I SHOULD NOT BE RUNNING");
  })(jQuery);
</script>

但是当我尝试使用以下代码添加编辑器的内容时:

function save(editor) {
    $(window).unbind('beforeunload');
    $("form[name='note'] input[name='note_title']").val($("#editor-title").val());
    $("form[name='note'] textarea[name='note_body']").html(editor.getValue());
    $("form[name='note'] input[name='version']").val("ace");
    $("form[name='note']").submit();
}

将弹出一个包含I SHOULD NOT BE RUNNING消息的消息框!!

我已将王牌编辑器绑定到以下内容:

<div id="editor" class="" style="display: none;"><?php echo htmlspecialchars($body) ?></div>

并使用以下方法运行 ace 编辑器:

window.editor = ace.edit("editor");
window.editor.getSession().setMode("ace/mode/markdown");
window.editor.commands.addCommand({
    name: 'save',
    bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
    exec: save
});

我的问题:

  1. 为什么 JavaScript 内容会运行?
  2. 如何防止它运行?

哎呀!! 我找到了原因!!
function save(editor)中,我应该添加不使用html()函数的编辑器内容;但有了val().

正确的save()函数是:

function save(editor) {
    $(window).unbind('beforeunload');
    $("form[name='note'] input[name='note_title']").val($("#editor-title").val());
    // WRONG [ IT WILL RUN THE JS ]
    // $("form[name='note'] textarea[name='note_body']").html(editor.getValue());
    // CORRECT
    $("form[name='note'] textarea[name='note_body']").val(editor.getValue());
    $("form[name='note'] input[name='version']").val("ace");
    $("form[name='note']").submit();
}

我发布我自己的问题的答案,也许以后可以帮助别人。 :)