fiddle - http://liveweave.com/YXhggg
我一直在尝试做的事情很简单。我想将以下代码动态添加到 Codemirror 中。
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>\n
如果我不添加脚本的 HTML,它会正常工作。 example
$(".jquery").click(function() {
editor.setCursor({line: 5 , ch : 0 });
editor.replaceRange("TAA DAA\n", editor.getCursor());
editor.focus();
});
但是当我这样做时就会发生这种情况。
控制台返回:SyntaxError: unterminated string literal
排除行错误为以下代码。
editor.replaceRange("<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>\n", editor.getCursor());
</script>
仍然存在问题在我尝试动态添加的代码中。
我想也许使用小于和大于符号可以解决问题......
editor.replaceRange("<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>\n", editor.getCursor());
但没有
我对如何解决这个问题感到困惑。
最佳答案
fiddle - http://liveweave.com/EyC98j
我查看了 Liveweave 的源代码,看看他们是如何做到的。
Liveweave 寻找您的<head>
标签并在其下方添加您的库。如果它没有 head 标签,它们会通过对话框建议提醒您。
// Append JS library to HTML <head>
function appendJSLib(txt) {
var textArea=htmlEditor.getValue();
var searchText = textArea.search("<head>");
if(searchText>0) {
txt = "<head>"+"\n"+txt;
var updatedTextArea = textArea.replace("<head>",txt);
htmlEditor.setValue(updatedTextArea);
}
else {
reset();
alertify.alert("<span style='color: #f5f5f5; padding:4px 6px 4px 6px; border-radius:3px; background-color: #cc0000;'>WARNING!</span><br/><br/> The <strong><head></strong> tag seems to be missing in your HTML. Although your code may still work, we highly recommened that you have a valid HTML syntax. Please refer to the structure of a correct HTML code below:<br/><br/><!DOCTYPE html><br/><html><br/><head><br/><title><!-- title --></title><br/> </head><br/> <body><br/> <!-- your content here --><br/> </body><br/></html>");
txt = txt+textArea;
htmlEditor.setLine(0, txt);
return false;
}
}
就我而言,我所需要的只是在 </
之后添加一个正斜杠。在</script>
像这样关闭代码..
editor.replaceRange("<"+"script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-latest.min.js\">"+"</"+"script"+">\n", editor.getCursor());
如果您想采用 Liveweave 的方式,您可以添加一个像这样的 js 库。
$("#jquery").click(function() {
txt="<"+"script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-latest.min.js\">"+"</"+"script"+">";
appendJSLib(txt);
});
关于javascript - Codemirror通过HTML动态添加JS SRC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25901682/