【问题标题】:How to add two <script> tag in one variable? [duplicate]如何在一个变量中添加两个 <script> 标签? [复制]
【发布时间】:2021-12-16 02:07:43
【问题描述】:

我正在使用一个变量来获取文本文件内容,其中文本文件将包含 HTML 元素

示例:test.txt

<main>
  <div> Example </div>
  <script async src="https://example.com/js/abc.js"></script>
  <script>(some inner text);</script><br>
</main>

获取txt文件

var contents = '&lt;?php print file_get_contents('abc/test.txt'); ?&gt;'; document.getElementById('replace_contents').innerHTML = htmlCode;

但我在控制台中遇到错误,例如

如果我检查得那么深,它会在 &lt;script async src="https://example.com/js/abc.js"&gt;&lt;/script&gt; 中显示一个错误,并且不会显示第二个&lt;script&gt; 标记..

即使我尝试过这个单独的

在上图中你可以看到&lt;/script&gt;不被认为是一个变量。

我不知道是什么原因造成的。 请帮我找到这个问题的答案...

【问题讨论】:

  • 似乎正确 - 您在 (some inner text); 上遇到 javascript 错误
  • 请分享更多细节。生成的标记看起来如何? “我会显示错误”——这是什么意思?
  • 不@FlashThunder,我在(some inner text); 上没有收到错误
  • @NicoHaase,我的错,它是“它会显示错误”
  • btw var contents = '&lt;?php print file_get_contents('abc'/test.txt'); ?&gt;'; 语法不正确...'abc' 部分正在结束引用...所以您通常会收到包含引号的 PHP 错误消息...使用 addslashes()htmlentities() 并将...('abc'/test.txt') 更改为...('abc/test.txt')

标签: javascript php script-tag


【解决方案1】:

在行尾使用\ 以允许字符串包含以下行。因为 Javascript 不像 PHP,所以字符串不会自动包含下一行。

例如: 而不是...

var lines = 'here is the first line
but the second line is not included'; // Error

You can write...

var lines = 'here is the first line\
and now the second line is included'; // Correct

Or use the + operator

var lines = 'here is the first line' +
'and I add the second line'; // Correct

【讨论】:

  • 不幸的是,这还不够。 HTML 解析器会将字符串的“”部分视为包含脚本的脚本元素的结束标记。
  • @amn 是的,我用不同的方式尝试了你所说的,但它并没有解决问题。即使我在文本文件中添加了&lt;br&gt;,但我得到了同样的错误
【解决方案2】:

你不能在另一个脚本标签中使用超过 1 个&lt;script&gt;&lt;/script&gt;

【讨论】:

  • 请分享更多细节。那是什么意思?为什么在另一个&lt;script&gt; 标记中甚至允许一个&lt;script&gt; 标记?
  • @NicoHaase 如果你看到上面的代码,你就会明白,一个&lt;script&gt;标签不在另一个里面
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2021-03-31
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
相关资源
最近更新 更多