2009-01-20 139 views
0

我想使用在http://ejohn.org/blog/processingjs/發現處理的JavaScript端口我想使用下面的構造函數。 Processing(CanvasElement, "some massive block of code");我知道javascript本身並不支持多行字符串,但有沒有辦法傳遞下面的內容,而不必連接每一行並轉義每個特殊字符?在javascript中包含特殊字符的多行字符串?

/** 
* Array. 
* 
* An array is a list of data. Each piece of data in an array 
* is identified by an index number representing its position in 
* the array. Arrays are zero based, which means that the first 
* element in the array is [0], the second element is [1], and so on. 
* In this example, an array named "coswav" is created and 
* filled with the cosine values. This data is displayed three 
* separate ways on the screen. 
*/ 

size(200, 200); 

float[] coswave = new float[width]; 

for (int i = 0; i < width; i++) { 
    float amount = map(i, 0, width, 0, PI); 
    coswave[i] = abs(cos(amount)); 
} 

for (int i = 0; i < width; i++) { 
    stroke(coswave[i]*255); 
    line(i, 0, i, height/3); 
} 

for (int i = 0; i < width; i++) { 
    stroke(coswave[i]*255/4); 
    line(i, height/3, i, height/3*2); 
} 

for (int i = 0; i < width; i++) { 
    stroke(255 - coswave[i]*255); 
    line(i, height/3*2, i, height); 
} 

回答

0

將「龐大的代碼塊」放在服務器上的自己的文件中,使用AJAX獲取並確保它具有合理的緩存標頭。

+0

這是一個快速和骯髒的問題解決方案,所以如果我可以避免的話,不想去ajax路線。看到這個問題。 http://stackoverflow.com/questions/460085/best-language-for-quickly-creating-user-interfaces-with-out-drag-and-drop – Jared 2009-01-20 12:20:21

3

的Javascript實際上不支持多行字符串:反斜槓追加到每行的末尾:

alert('1\ 
    2\ 
    3'); 

不是很漂亮,但它的作品。

另一種方法是使用腳本文字編碼...我建議PHP,因爲它是一個1班輪:

<?=json_encode('your text');?> 
+0

+1。我認爲我知道Javascript語法的每一個細微差別。很好的答案。 – AnthonyWJones 2009-01-20 12:53:58

0

或者,你可以把文字在HTML頁面(隱藏,例如),並從那裏得到它...

0

另一種選擇是使用E4X文字

var s = "" + <r><![CDATA[ 
line 1 
line 2 
]]></r>; 

雖然我懷疑它是由IE6的支持。

+0

它甚至不支持IE7 – Greg 2009-01-20 12:43:41

1

對於一個更易於維護的解決方案,我將它放在腳本標記標籤在頁面的主體,如:

<script type="text/processing" id="code"> 
/** 
* Array. 
* ... 
*/ 

size(200, 200); 
... 
</script> 

,構建你的處理對象,如:

var canvas = document.getElementById('canvas'); 
var code = document.getElementById('code'); 
Processing(canvas , code.textContent); 

對於快速和骯髒的解決方案通過一個JSON編碼器運行你的處理代碼,如RoBorg suggested,你會得到一個字符串,你可以複製並粘貼到第二個參數。