在javascript中包含特殊字符的多行字符串?
我想使用在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);
}
将“庞大的代码块”放在服务器上的自己的文件中,使用AJAX获取并确保它具有合理的缓存标头。
的Javascript实际上不支持多行字符串:反斜杠追加到每行的末尾:
alert('1\
2\
3');
不是很漂亮,但它的作品。
另一种方法是使用脚本文字编码...我建议PHP,因为它是一个1班轮:
<?=json_encode('your text');?>
+1。我认为我知道Javascript语法的每一个细微差别。很好的答案。 – AnthonyWJones 2009-01-20 12:53:58
或者,你可以把文字在HTML页面(隐藏,例如),并从那里得到它...
另一种选择是使用E4X文字
var s = "" + <r><![CDATA[
line 1
line 2
]]></r>;
虽然我怀疑它是由IE6的支持。
它甚至不支持IE7 – Greg 2009-01-20 12:43:41
对于一个更易于维护的解决方案,我将它放在脚本标记标签在页面的主体,如:
<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,你会得到一个字符串,你可以复制并粘贴到第二个参数。
这是一个快速和肮脏的问题解决方案,所以如果我可以避免的话,不想去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