2013-11-20 211 views
0

我試圖創建兩個單獨的HTML文檔:main.htmlsufler.html。想法是控制sufler.htmlmain.html。到目前爲止,我成功地寫了文本並改變了它的字體風格。但字體樣式只改變一次 ... 我需要它可以改變很多次,不明白是怎麼回事,因爲我的理解,每次我調用函數writing()時,我用newDoc.body.innerHTML = ''清除所有新文件的內容...但似乎不是......儘管文本每次都在變化。Javascript appendChild(腳本)只能運行一次

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

任何一個節點只能被添加到文檔一次。您只定義script一次,但試圖將其添加到DOM多次。將var script = ...線放入writing()

+0

謝謝,它的工作原理!感覺很愚蠢:D –