jQuery html()和换行符 [英] jQuery html() and new line characters
问题描述
我正在使用带有rails的jQuery并拥有以下代码
I'm using jQuery with rails and have the following piece of code
$('#related').html("<%= render :partial => "related_items" %>");
我在浏览器中遇到问题,其中#related元素的内容仅被替换部分中没有换行符。
I'm having a problem in the browser where the content of the #related element is only being replaced when there are no line breaks in the partial.
这不是什么大不了的事,我可以将所有内容放在一行但是它使代码非常难以阅读。
This isn't too much of a big deal, I can place everything on one one line but it makes the code very difficult to read.
有没有办法在jQuery html()属性中省略换行符?
Is there a way around having to omit line breaks in the jQuery html() attribute?
推荐答案
这里发生的是<%
和%> $ c之间的代码首先由Rails解释$ c>,并将该解释的输出发送到浏览器。那么发送到浏览器的是:
Whats happening here is the code between the <%
and %>
is being interpreted by Rails first, and the output of that interpretation is being sent to the browser. So what's being sent to the browser is:
$('#related').html("Some text with a
line break in it");
这不是有效的javascript,因为javascript不允许使用多行双引号字符串。你需要转义字符串中的换行符,这样当它们打印到浏览器时,结果就是一个有效的javascript语句。
This is not valid javascript because javascript doesn't allow multi-line double-quoted strings. You need to escape the line breaks in the string so that when they are printed to the browser the result is a valid javascript statement.
这篇关于jQuery html()和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!