简体   繁体   English

如何使用javascript在主体部分插入html内容

[英]How to insert html content in body part using javascript

I am trying to insert string inside body part of my html document using javascipt. 我正在尝试使用javascipt将字符串插入html文档的正文部分。 The string which i want to insert contains some script tags also. 我要插入的字符串也包含一些脚本标签。 For example : 例如 :

  var str = "<div> some text </div>
             <script src='/Scripts/jquery-1.7.2.js' type='text/javascript'></script>";

Now when i insert the above string using jquery , like : 现在,当我使用jquery插入上述字符串时,例如:

 $('body').html(str);

It will insert the string and load the jquery also. 它将插入字符串并加载jquery。 But when i insert this string using javascript, like : 但是当我使用javascript插入此字符串时,例如:

document.getElementsByTagName('body')[0].innerHTML = str;

This will not load the jquery script in the browser. 这不会在浏览器中加载jquery脚本。 Can anyone tell me how can i achieve the same using javascript ? 谁能告诉我如何使用javascript达到相同的目的?

http://www.jquery4u.com/javascript/dynamically-load-jquery-library-javascript/ here you have a good guide. http://www.jquery4u.com/javascript/dynamically-load-jquery-library-javascript/在这里您有一个很好的指南。 So in your case you can try this: 因此,您可以尝试以下方法:

  var head= document.getElementsByTagName('body')[0];
  var script= document.createElement('script');
  script.type= 'text/javascript';
  script.src= '/Scripts/jquery-1.7.2.js';
  head.appendChild(script)

Problem is, that if you are inserting scripts with innerHTML, the scripts will not be executed. 问题是,如果您要插入带有innerHTML的脚本,则这些脚本将不会执行。 No browser will do this because of security issues. 由于安全问题,任何浏览器都不会这样做。 jquery implemented a way around this. jQuery实现了解决此问题的方法。 You can find further information and a solution in pure javascript here: Executing <script> elements inserted with .innerHTML 您可以在这里找到纯JavaScript的更多信息和解决方案: 执行.innerHTML插入的<script>元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM