我正在构建一个代码编辑器,下面是我的代码:
<template>
<div>
<textarea
id="html"
placeholder="HTML"
></textarea>
<textarea
id="css"
placeholder="CSS"
></textarea>
<textarea
id="js"
placeholder="JavaScript"
></textarea>
<iframe id="code"></iframe>
</div>
</template>
<script>
export default {
name: 'code-editor',
mounted () {
this.compile();
},
methods: {
compile () {
var html = document.getElementById("html");
var css = document.getElementById("css");
var js = document.getElementById("js");
var code = document.getElementById("code").contentWindow.document;
document.body.onkeyup = function () {
code.open();
code.writeln(
`${html.value} <style> ${css.value} </style> <script> ${js.value} <script> `
);
code.close();
};
}
}
}
</script>
<style>
textarea {
width: 32%;
/* float: top; */
min-height: 250px;
overflow: scroll;
margin: auto;
display: inline-block;
background: #f4f4f9;
outline: none;
font-family: Courier, sans-serif;
font-size: 14px;
}
iframe {
bottom: 0;
position: relative;
width: 100%;
height: 35em;
}
</style>
在我的 onkeyup
里面writeln
中的函数命令,使用上面的字符串我得到这个错误: error in ./src/components/CodeEditor.vue?vue&type=script&lang=js&
Syntax Error: Unterminated template (35:75)
33 | code.open();
34 | code.writeln(
> 35 | `${html.value} <style> ${css.value} </style> <script> ${js.value}
| ^
但是如果我删除 </script>
来自它工作的字符串的标签。我不知道为什么它不接受关闭标签。任何人都可以向我解释这一点吗?有什么办法让它接受
</script>
标签?
最佳答案
您需要它来破解 </script>
进入 "<" + "/script>"
以便 HTML 解析器不会将其解释为结束标记。你也可以做<\/script>
.
它是如何工作的一个例子:
<script>
console.log("hello <\/script>");
console.log("hello <" + "/script>");
</script>
以及它如何不起作用的示例(使用普通
</script>
将被解释为结束标记):<script>
console.log("hello </script>");
</script>
如果您想在反引号内使用它,仍然相同(根据 OP 的评论添加):
<script>
let foo = "foo";
console.log(`hello ${foo} <\/script>`);
</script>
关于javascript - 字符串不接受 </script> 的结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66192561/