The only way to fix it was using google chrome/IE10+ Just can't make it work on IE8.
我正在尝试将一些脚本 append 到我的网页,但我不想使用任何 Jquery。
这确实有效,但它在第三行使用了 jquery。
var element = document.getElementById("contentSCRIPT");
element.parentNode.removeChild(element); // this removes the div and all the javascript inside it
$('<div id="contentSCRIPT"></div>').appendTo(document.getElementById("main")); // this adds again the content to the page
$('<script>' + document.getElementById("textSCRIPT").value + ' ;</' + 'script>').appendTo(document.getElementById("contentSCRIPT")); // in here i try to add the javascript code back to the content.
我尝试过:
var content = document.createTextNode('<div id="contentSCRIPT"></div>');
document.getElementById("main").appendChild(content);
但它将我的脚本(内容)添加为 HTML 而不是代码。
有什么解决办法吗? 谢谢!
编辑:
我必须创建 contentScript,因为我想从页面中删除该脚本并多次添加另一个脚本。
我尝试过
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
document.getElementById('contentSCRIPT').innerHTML = document.getElementById('textoSCRIPT').value;
document.getElementById("main").appendChild(contentScript);
但是,这会将代码添加为 HTML(在页面上显示为标签),并且不会添加到 DOM。
最佳答案
$('<div id="contentSCRIPT"></div>')
在javascript中可以写成如下:
var contentScript = document.createElement("div");
contentScript.setAttribute("id", "contentSCRIPT");
执行 jQuery 的 appendTo
,您想要 appendChild
在父级上:
document.getElementById("main").appendChild(contentScript);
同样,对于第四行:
var script = document.createElement("script");
script.innerHTML = document.getElementById('textSCRIPT').value;
contentScript.appendChild(script);
编辑
根据您编辑的信息,您不需要创建 div 来保存 contentScript。只需在脚本上添加一个 id 即可:
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
contentScript.innerHTML = document.getElementById('textSCRIPT').value;
document.getElementById("main").appendChild(contentScript);
关于javascript - 不使用 JQUERY 将脚本 append 到 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004933/