我有一个名为
在外部网站中,我有这个脚本
我想在多个 Html
那么我该如何修改
到目前为止,我已经尝试在
无论我们在哪里放置
编辑:
sample.js
的文件,其中包含:document.write('<script>........</script><a>...</a><style>....</style>');
在外部网站中,我有这个脚本
<script src="https://example.com/sample.js"></script>
。无论在哪里使用此脚本,sample.js
都会立即加载。即使我使用了 document.write
,所有其他元素也不会被删除。我想在多个 Html
<div>
或其他元素中加载上述脚本,其中我们定义类似于 id="example"
或 class="example"
或 data-sample-js
的内容。那么我该如何修改
sample.js
文件以实现这一点?到目前为止,我已经尝试在
sample.js
中:window.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll("[data-sample-js]").forEach(elem => {
elem.innerHTML = document.write('<script>...</script><a>...</a><style>...</style>');
});});
无论我们在哪里放置
<script src="https://example.com/sample.js"></script>
以及 <div data-sample-js></div>
,JavaScript 都会被加载,但它会删除页面中的所有其他 HTML 元素。编辑:
There is a full html document is placed in the document.write().
It can have multiple scripts, styles, metas and all other possible codes.
that will be present in a static html webpage, including <script src="...">
document.write
,因为它包含script
和style
元素。 - lisdoadocument.write
。查看此链接以了解有关脚本的更多信息:https://dev59.com/cnA75IYBdhLWcg3wg5fs,您可以使用`document.createElement`来创建样式(或者只需使用`document.head.innerHTML += ...`添加样式)。 - Hive7