如何通过jQuery插入JavaScript代码? [英] how to insert javascript code via jquery?

查看:111
本文介绍了如何通过jQuery插入JavaScript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





<div id="example">

</div>


<script type="text/javascript">

  function insert() {
     var data = '<script type="text/javascript">  function test() {    a = 5;   }<\/script>';  
     $("#example").append(data);
  } 

  function get() {
     var content = $("#example").html();
     alert(content);
  }


</script>


<a href="#" onclick="insert();">INSERT</a>

<a href="#" onclick="get();">GET</a>


</body>
</html>

我想做什么:

当我单击插入时,我想将此代码插入到示例div中:

when i click on insert, i want to insert this code into example div:

<script type="text/javascript">  function test() {    a = 5;   }<\/script>

当我单击获取"时,我想要获取插入到那里的代码.

when i click on get, i want to get that code, which i inserted there.

但是当我单击insert,然后单击get时,没有代码..问题出在哪里?谢谢

but when i click on insert, and then on get, there's no code.. where is problem ? thanks

推荐答案

根据对亚当·贝莱尔(Adam Bellaire)的评论,您希望script标记显示为普通文本.您要做的是使用 HTML实体对文本进行编码,这将阻止浏览器将其作为普通HTML进行处理.

According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.

   var enc = $('<div/>').text('<script type="text/javascript">  function test() {    a = 5;   }<\/script>').html();
   $("#example").append(enc);

这篇关于如何通过jQuery插入JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆