Javascript appendChild(script)只能工作一次

Javascript appendChild(script) works only one time

本文关键字:一次 工作 appendChild script Javascript      更新时间:2023-09-26

我正在尝试创建两个独立的HTML文档:main.HTMLsufler.HTML。想法是从main控制subfler.HTML页面。到目前为止,我成功地编写了文本并更改了它的字体样式。但字体样式仅更改一次。。。

我需要它能够多次更改,无法理解发生了什么,因为,据我所知,每次调用函数writing()时,我都会用newDoc.body.innerHTML = ''清除所有新文档的内容。。。但似乎不是。。。尽管文本每次都在变化。

main.html

<html>
<head>
<script type="text/javascript">
var HTMLstringPage1     = '<!DOCTYPE html><html><head><link href="stilius.css" rel="stylesheet" type="text/css" /></head><body>',
    HTMLstringPage2     = '</body></html>',
    HTMLstringDiv1      = '<div id="sufler"><div id="mov"><p id="flip">',
    HTMLstringDiv2      = '</p></div></div>';
//NEW WINDOW OPEN--------------------------------------------------------------------------------------------------------
var newWindow   = window.open('suffler.html','_blank','toolbar=no, scrollbars=no, resizable=no, height=615,width=815'); 
var newDoc      = newWindow.document;
                  newDoc.write(HTMLstringPage1,HTMLstringDiv1+'Text'+HTMLstringDiv2,HTMLstringPage2);
var script      = newDoc.createElement("script");
                  script.type = "text/javascript";
//=======================================================================================================================
//WRITING----------------------------------------------------------------------------------------------------------------
function writing(){
    newText =   document.getElementById("sel-1").value.replace(/'n/gi, "</br>");
    fontas=     document.getElementById("textFont").value;
    size=       document.getElementById("textSyze").value;
    stylas=     document.getElementById("textStyle").value;
    syntax=     document.getElementById("textSyntax").value;
    newDoc.body.innerHTML = '';//clears old text (should clear old scripts and functions too)
    newDoc.write(HTMLstringPage1,HTMLstringDiv1,newText,HTMLstringDiv2,HTMLstringPage2);//writes new text (and new scripts and functions)
    
var text        = newDoc.createTextNode('document.getElementById("flip").style.font="'+stylas+' '+syntax+' '+size+'px '+fontas+'";');
    script.appendChild(text);
    newDoc.getElementsByTagName("body")[0].appendChild(script);
}
//=======================================================================================================================
</script>
</head>
<body>
    <button type="button" style="background-color: #F5FF25;" onclick="writing()">Apply     text</button>
</body>
</html>

任何一个节点只能添加到文档中一次。您只定义了一次script,但多次尝试将其添加到DOM中。将var script = ...线放在writing()内。