在jQuery脚本中避免HTML-in-string / html() [英] Avoiding HTML-in-string / html() in a jQuery script
问题描述
我通过将HTML存储在JavaScript字符串中的弹出窗口中对其进行了原型设计变量,然后显示该字符串:
$('#pop_div')。html(string);
其中 string
定义如下: p>
var string ='< div class =className>'+
'HTML Content'+
'< / div>'
我曾见过一些网站,但认为它是不正确的。
它适用于静态html代码片段,但不适用于使用<%= ..%>
生成的html代码$ b $
谢谢
< script> var string =h2_lin>解决方案
<%= escape_javascript(...)=>;< / script>
因为 escape_javascript
原始字符串将被JavaScript解释器正确解释。
请参阅为什么在渲染局部变量之前使用escape_javascript?以获得更多讨论。
请注意,如果您想将此在 onclick
处理程序中,而不是在< script>
元素中,您可能需要 escape_javascript
然后HTML转义结果。
I want to make a jQuery based custom popup window for my site using javascript.
I prototyped it by storing the HTML to go in the popup inside a javascript string variable and then display that string thus:
$('#pop_div').html(string);
where string
is defined thus:
var string= '<div class="className">' +
'HTML Content'+
'</div>'
I've seen a few websites that do this but think it is incorrect.
It works for static html snippets but not for rails generated html using <%= .. %>
What is the best way of loading HTML code generated by rails into a javascript/jquery script?
thanks
It is fine to do
<script>var string = <%= escape_javascript(...) =>;</script>
since the escape_javascript
does the work of ensuring that the original string will be interpreted properly by the JavaScript interpreter.
See Why escape_javascript before rendering a partial? for more discussion.
Note, that if you want to put this in an onclick
handler instead of inside a <script>
element you may need to escape_javascript
and then HTML escape the result.
这篇关于在jQuery脚本中避免HTML-in-string / html()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!