我正在尝试保存 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
});
我的问题:
- 为什么 JavaScript 内容会运行?
- 如何阻止它运行?
最佳答案
哎呀!!我找到了原因!!!
在 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/