如何在浏览器DOM中插入诸如def sum_with_while(min, max)
# CONSTRAINT: you should use a while..end structure
array = (min..max).to_a
sum = 0
count = 0
if min > max
return -1
else
while count < array.length
sum += array[count]
count += 1
end
end
return sum
end
之类的任何字符串,然后在浏览器控制台中看到“有效”?
jQuery的append函数可做的事情:
<script>console.log('it works');</script>
但我正在寻找简便的解决方案,最好是普通js
上下文:字符串可以像$('html').append('<script>console.log('it works');
一样复杂-它应该在DOM中呈现正确的位置,并由所有JS人员完成
答案 0 :(得分:2)
您可以使用insertAdjacentHTML
插入HTML,然后返回并查找脚本并复制脚本src
或文本,然后将副本插入DOM中以运行它:
// Sticking with broadly-supported features:
var htmlString = "<div><h1>Title</h1></div><div><script>console.log('it works');<\/script></div>";
var target = document.getElementById("target");
target.insertAdjacentHTML("beforeend", htmlString);
var scripts = target.getElementsByTagName("script");
while (scripts.length) {
var script = scripts[0];
script.parentNode.removeChild(script);
var newScript = document.createElement("script");
if (script.src) {
newScript.src = script.src;
} else if (script.textContent) {
newScript.textContent = script.textContent;
} else if (script.innerText) {
newScript.innerText = script.innerText;
}
document.body.appendChild(newScript);
}
<div id="target"></div>
注意:任何内嵌document.write
语句都不会像在页面的初始解析中那样有效。相反,他们将重新打开该文档并将其所有内容替换为其所写的内容。