我正在尝试使用innerHTML替换div的内容。
以下是我的HTML的重要部分:
<script> function replace() {
document.getElementById("area").innerHTML = '<script type="text/javascript" src="SOMELINK"></script>';
</script>
<button onclick=replace()> replace </button>
<div id = "area"> hello </div>
单击该按钮时,我希望div #area被脚本替换,以便显示链接的内容。我可以使用innerHTML将其替换为明文,例如将“hello”替换为“Hello World”,但是当我包含标签时,根本不显示任何内容。如果我删除标签,则标签内的其余网址会显示出来。关于我可能做错了什么的想法,以及我如何使用javascript用脚本对象替换div?
编辑:我输错了脚本标签,但现在已经修好了!
答案 0 :(得分:1)
您的脚本标记格式错误,通过innerHTML
插入脚本并不会执行该脚本。您可以创建一个脚本元素并附加它,如果您希望它加载源或执行其内部内容。
var area = document.getElementById('area'),
script = document.createElement('script'); // Create the script
// Set the script source
script.src = 'myAwesomeScript.js';
// Remove the contents of the DIV
area.innerHTML = '';
// But why would you nest a script inside of a DIV, anyway?
area.appendChild(script); // Append it
如果您确实想用脚本标记替换整个DIV:
var area = document.getElementById('area');
// * elem is the element to replace
// * src is the script's source
function replaceWithScript(elem, src) {
var script = document.createElement('script');
script.src = src;
// Insert script after elem
elem.parentNode.insertBefore(script, elem.nextSibling);
// Remove elem. Now script has its position, and it looks
// like it replaced it.
elem.parentNode.removeChild(elem);
}
replaceWithScript(area, 'myAwesomeScript.js');
最后,如果您希望脚本显示为文本,那么它只是:
document.getElementById('area').innerText = '<script src="farboo.js"></script>';
答案 1 :(得分:0)
如果你提供格式良好的HTML
,它应该有效document.getElementById("area").innerHTML =
'<script type="text/javascript" src="SOMELINK"></script>';
(你错过了结束标签)