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

标签 javascript editor markdown ace-editor

我正在尝试保存 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消息的消息框!!!

我已将 ace 编辑器绑定(bind)到以下内容:

<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();
}

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

关于javascript - 为什么 Javascript 代码在尝试保存 ACE 编辑器的内容时​​会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922170/

相关文章:

emacs - 在emacs中可以快速(重复)撤消吗?

java - 由于文件重命名导致输入更改时更改编辑器上的标题

markdown - Mermaid 中的全局或文档范围样式

javascript - 考虑到我的具体情况,是否有比 Array.map() 更高效地遍历 JSON 的方法?

javascript - setInterval 在声明为全局时不起作用

javascript - 在 setInterval( ) 之后,单击功能将不起作用...变量不再递增

python - 使用指定的 css Markdown 到 html

javascript - 在 React 中使用 Vidyard 嵌入式播放器

visual-studio-code - 使用 VSCode 对 Python 进行实时 linting

html - Markdown 到 HTML