Javascript appendChild(脚本)只能工作一次

时间:2013-11-20 14:13:25

标签: javascript text window edit appendchild

我正在尝试创建两个单独的HTML文档: main.html sufler.html 。想法是从 main.html 控制 sufler.html 页面。到目前为止,我成功地编写了文本并更改了它的字体样式。但字体样式只改变一次 ... 我需要它能够改变很多次,无法理解发生了什么, 因为,据我所知,每次调用函数writing()时,我都会用newDoc.body.innerHTML = ''清除所有新文档的内容......但似乎不是......尽管文本每次都在变化。 / p>

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;
    synttax=    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+' '+synttax+' '+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>

1 个答案:

答案 0 :(得分:1)

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