例如,
var newElement = document.createElement('div');
newElement.innerHTML = "<p>new content</p><script>alert('Hello World!')</script>";
element.appendChild(newElement);
结果:“新内容”被附加到页面中,但不会有警告说“Hello World!”
我尝试过innerHTML、insertAdjacentHTML、append、appendChild 方法。但问题是 JS 和 CSS 没有动态加载。
在 jQuery 中,after()
可以工作👍🏻
$(selector).after("<p>new content</p><script>alert('Hello World!')</script>");
是否有纯 JavaScript 的等价物?
最佳答案
您可以使用eval
以字符串格式执行脚本。 jQuery 还在 DOM 操作的某些部分中使用了 eval
。
const content = "<p>new content<\/p><script>alert('Hello World!')<\/script>";
const newElement = document.createElement('div');
newElement.innerHTML = content
const scriptRegex = /(?<=<script>)(.*)(?=<\/script>)/g; //get scripts between script tags
const scripts = content.match(scriptRegex);
for(const script of scripts) {
eval(script) //execute your string as a script
}
document.getElementById("content").appendChild(newElement);
<div id="content"></div>
旁注,对于您的情况,没有所谓的安全方法将字符串转换为脚本,因为有人可能会将恶意脚本注入(inject)您的字符串并在您不通知的情况下执行它们,因此您需要确保你所有的琴弦都在你的控制之下。您可以查看XSS attack为了更好的理解。
关于javascript - 如何使用纯javascript在当前网页中附加带有CSS、JS的HTML内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71831231/