[英]Load partial html with javascript inside
On my website I load html, which is rendered at the server (nodejs), and insert it at the right position (most time a div with id content). 在我的网站上,我加载了html,它在服务器(nodejs)上呈现,并将其插入到正确的位置(大多数时候是一个带有id内容的div)。
How would I insert the received html on the client, so that included script tags are executed? 如何在客户端上插入收到的html,以便执行包含的脚本标记?
I am using on the client side underscore and handlebars. 我在客户端使用下划线和把手。 But vanillajs is also possible of course.
但是vanillajs当然也是可能的。
PS: Here is an example to show the difference between jQuery.html()
and setting the innerHTML
-property: PS:这是一个示例,用于显示
jQuery.html()
和设置innerHTML
-property之间的区别:
http://jsfiddle.net/waxolunist/VDYgU/3/ http://jsfiddle.net/waxolunist/VDYgU/3/
with jQuery 用jQuery
$('div#content').html(loaded_html);
without: 无:
getElementById('content').innerHTML = loaded_html;
While possible to do it your way, a better idea might be to send json and render pages in the browser using the same templates you (possibly) use in the server. 虽然可以按照自己的方式进行,但更好的想法可能是使用您(可能)在服务器中使用的相同模板在浏览器中发送json和呈现页面。 I'm using doT, which I think to be the best of all JavaScript based templates (like EJS, underscore).
我正在使用doT,我认为它是所有基于JavaScript的模板中最好的(如EJS,下划线)。
You could leverage jQuery to do that. 你可以利用jQuery来做到这一点。 Just with
只是
$.load("#divname").load(url) $ .load( “#divname”)。负载(URL)
There is some problem with your character escaping, please use jshint
. 你的角色逃脱有一些问题,请使用
jshint
。 Otherwise it is pretty simple to use like 否则使用起来非常简单
var script1 = "content for jQuery";
var script2 = "content for javascript";
$(document).ready(function (){
$('#content1').html(script1);
document.getElementById('content2').innerHTML = script2;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.