簡體   English   中英

字符串不接受關閉標簽

[英]String doesn't accept the close tag for </script>

我正在構建一個代碼編輯器,下面是我的代碼:

<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>

writeln命令中的onkeyup function 中,使用上面的字符串,我收到此錯誤:

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM