简体   繁体   English

如何在网页中多次加载包含 document.write 的 Javascript?

[英]How do I load a Javascript which contains document.write multiple times in a webpage?

I have a javascript code presented in the head tag:我在 head 标签中有一个 javascript 代码:

document.write('<script>..</script><style>..</style><a></a><script src".."></script>');

The code inside the document.write() is actually an html document of a sample webpage with scripts , styles , metas and all other possible elements. document.write()中的代码实际上是一个示例网页的metas文档,其中包含scriptsstyles 、元数据和所有其他可能的元素。

Now i need to run this javascript code each time in any element where sample-js-doc attribute tag is presented in the body .现在我需要每次在body中出现sample-js-doc属性标签的任何元素中运行这个 javascript 代码。 For example: <div sample-js-doc ></div> or <a sample-js-doc ></a>例如: <div sample-js-doc ></div><a sample-js-doc ></a>

Currently, where-ever I place the javascrit, the content loads there quickly.目前,无论我将 javascrit 放在哪里,内容都会快速加载到那里。 That's look good.那看起来不错。 But I need it also to be invoked in other places where sample-js-doc attribute tag is present.但我还需要在存在sample-js-doc属性标签的其他地方调用它。

How do I modify the javascript code to achieve this without removing all other elements present in the webpage?如何修改 javascript 代码以实现此目的而不删除网页中存在的所有其他元素?

Use querySelectorAll使用querySelectorAll

var els = document.querySelectorAll('[sample-js-doc]');

for (i = 0; i < els.length; i++) {
    els[i].innerHTML = '<script>..</script><style>..</style><a></a><script src".."></script>';
}

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

相关问题 如何使用document.write用javascript加载脚本 - how to load a script with a document.write with javascript 如何使用document.write()创建JavaScript来执行? - How do I get JavaScript created with document.write() to execute? JavaScript:多个 Document.Write - JavaScript: Multiple Document.Write 如何异步加载具有document.write的第三方javascript标记 - How to load third-party javascript tag asynchronously which has document.write 你如何用 document.write 写出 JavaScript 代码? - How do you write out JavaScript code with document.write? 如何在不使用document.write的情况下将多个js文件加载到单个javascript文件中? - How to load the multiple js files in single javascript file, without using document.write? 如何在createElement中加载带有document.write的javascript文件? - How can I load a javascript file with document.write inside of createElement? 使用document.write()加载javascript - Using document.write() to load javascript 如何在不使用document.write()的情况下在Javascript中开始新行? - How do I start a new line in Javascript without using document.write()? javascript新手,如何更改-&gt; document.write(schedule [row] [&#39;title&#39;]))的颜色; 变成红色? - new to javascript, how do i change color of --> document.write(schedule[row]['title']); to red?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM