2013-07-08 48 views
1

嘿,我已经编写了一段JavaScript生成Html代码,我试图将代码保存为字符串,然后将其复制到<textarea>但由于某种原因,当我使用escape()它在Google Chrome中显示Uncaught SyntaxError: Unexpected token ILLEGAL。我不知道为什么,这是我的代码Javascript无法转义Html字符串

  document.getElementById("share").value=escape(' 
<script src="main.js"></script> 
<script src="event.js"></script> 
<script src= "init.js"></script> 
<script src= "util.js"></script> 
<link rel="stylesheet" type="text/css" href="style.css"> 
<canvas width="1280" height="500" id="header_canvas"  >Please Update your browser to view this page</canvas> 
<canvas width="1280" height="500" id="sub_header_canvas" >Please Update your browser to view this page</canvas> 

<script> 
function submit() 
{ 
    header_text     ='+document.getElementById("title").value+'; 
    cover_time_pan    ='+document.getElementById("cover_turn_time").value+'; 
    cover_turn_pause_time  ='+document.getElementById("cover_turn_pause").value+'; 
    text_time_pan    ='+document.getElementById("text_turn_time").value+'; 
    text_turn_pause_time  ='+document.getElementById("text_turn_pause").value+'; 
    header_reverse    ='+document.getElementById("reverse").checked+'; 
    header_grad_percent  ='+document.getElementById("grad_height").value+'; 
    header_grad_color  ='+document.getElementById("grad_colour").value+'; 

    ct0.src     ='+document.getElementById("ct0").value+'; 
    ct1.src     ='+document.getElementById("ct1").value+'; 
    ct2.src     ='+document.getElementById("ct2").value+'; 

    tt0.src     ='+document.getElementById("tt0").value+'; 
    tt1.src     ='+document.getElementById("tt1").value+'; 
    tt2.src     ='+document.getElementById("tt2").value+'; 

    cover_textures[0]=ct0; 
    cover_textures[1]=ct1; 
    cover_textures[2]=ct2; 
    text_textures[0]=tt0; 
    text_textures[1]=tt1; 
     text_textures[2]=tt2; 


    resize_window(); 
} 
</script>  
<script> 
    init_all(); 
    submit(); 
</script> 

'); 
+1

我已经回答了类似的问题[这里](http://stackoverflow.com/a/17344985/1053938)。问题在于字符串的“”部分。你甚至需要在字符串“<\/script>”内跳过。 – jonhopkins

+0

哦,甜蜜现在明白了,非常感谢你! –

回答

3

问题是因为JavaScript字符串必须在换行符之前终止。 \ n存在的原因是允许开发人员轻松地将换行符(ASCII:10)放入字符串中。

因此,例如,当你有一个字符串,它看起来像这样:

//Note terminating double quote is not there , similar to your code 
var foo = "Bob 

您的代码将在这一点上有一个语法错误并停止运行。

如果您希望在多行字符串,你必须插入一个反斜杠字符“\”你终止只是前行,像这样:

//Correct way of writing code 
var foo = "Bob \ 
is \ 
cool."; 

但是该字符串将不包含\ n个字符在字符串被分解成单独的行的位置。将换行符插入字符串的唯一方法是插入一个值为10的字符,其中最简单的方法就是\ n转义字符。

var foo = "Bob\nis\ncool."; 
+0

谢谢我得到它逃脱\ n但现在我坚持所有的前进/ S不断提出相同的错误,是他们逃脱他们更容易的方式/或我可以使用/? @hsemarap –