2013-07-08 45 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 –