Avoiding HTML-in-string / html() in a jQuery script

萝らか妹 提交于 2020-01-06 20:17:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!