在JavaScript函数中插入多行字符串作为变量

我想通过RJS插入一个取自textarea的多行字符串。 这样做:

$('#description').text(''); 

不起作用,因为它会生成这样的东西:

 $('#description').text('

first line
second line

fourth line

');

因为字符串不在一行上,所以JS调用失败。 那么现在simple_format正确地格式化了字符串,我怎样才能将它全部打印在我的RJS文件中的一行?

试试这个:

 $('#description').text('<%= simple_format(description).gsub("\n", "\\n").gsub("\r", "\\r").gsub("\t", "\\t").gsub("'","\\'") %>'); 

这将使用Javascript理解的转义序列替换换行符。 类似于其他字符,如回车和制表符。 此外,它将’字符串定义字符替换为带有转义序列的字符,以便诸如“It’s mine”之类的字符串不会引起任何意外。

你可以(最好)使用内置的escape_javascript()j()方法:

 $('#description').text('<%= j(simple_format(description)) %>'); 

http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript