繁体   English   中英

如何正确地将 Javascript 包含在 javascript 中?

[英]How to Include Javascript inside javascript properly?

我被迫将代码放在插入时适用于数千个 web 页的位置。

我只想在 URL 包含以下内容时使用脚本:“/pN2toKYZ/checkout”:

这是我正在尝试的,我也尝试过 escaping bthe starting'<' 但它没有用

<script>
if (window.location.href.indexOf('/pN2toKYZ/checkout') != -1) {
   document.write("<script>
  gtag('event', 'conversion', {'send_to': 'AW-834461893/ixLXCK-Wm6kDEMXB840D'});
 <\/script>
")
}
</script>

您问题中显示的版本有换行符,这在字符串中是不允许的。 您可能已将它们放在此处进行演示,但请确保它们不在您的实际代码中。

如果您必须使用document.write ,则无需在document.write的引号字符串参数中转义任何内容(如果它包含与您用来引用它的引号相同的引号,则需要转义它们,但标签等都可以) .

虽然我不明白为什么你的条件中的“创建”脚本中指定的命令不能简单地直接放在你的条件中(不需要向页面编写新脚本),但如果我必须添加一个由创建的脚本一个脚本,我会创建一个新的脚本元素,将 innerText 添加到它指定所需的命令,然后 append 将脚本元素添加到文档中。

如果您添加的脚本需要放置在页面的特定部分(而不是像我的示例那样附加为正文的最后一个子节点),您可以在此处了解更多信息: How to append a childnode to a specific position

以下示例有一个脚本,它使用单个命令创建一个新脚本来更改页面背景颜色。 CSS 已用于显示渲染的 html 中的实际脚本(仅供演示,与功能无关)。 您将看到创建的脚本已添加到页面并执行。

 let newScript = document.createElement('script'); newScript.innerText = "document.body.style='background: red';"; document.body.appendChild(newScript);
 body { background: blue; } /*make scripts visible in html*/ script { display: inline-block; border: 1px solid black; padding: 10px; white-space: pre-wrap; font-family: monospace; color: #00ff00; background: #005500; margin-bottom: 20px; }
 <h1> page with a single script</h1> <p>The background color of the page is set to BLUE in the accompanying style sheet</p> <p>This page has a single script tag included in its html. The script creates a new script element, adds a command to it, and appends the script to the page</p> <p>the script added by js then changes the page background to red</p> <p>both scripts are shown below in the rendered html (because the accompanying styles make them visible) but only the first one is written as a script in the original html</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM