问题
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
回答1:
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.
回答2:
It would be easier to store the element in a variable:
var el = $("<div class='className' />").html("HTML Content");
//append the element to the div
$("#pop_div").append(el);
回答3:
How about in 3 steps:
var htmlContent = 'HTML Content';
var elem = $('<div />').addClass("className").html(htmlContent);
$('#pop_div').empty().append(elem);
Now, I've only done "hello world" with RoR, but use Mike Samuel's escape_javascript
code and that might address your needs.
来源:https://stackoverflow.com/questions/8069663/avoiding-html-in-string-html-in-a-jquery-script