how to insert javascript code via jquery?

2020-06-23 06:44发布



<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>

what i want to do:

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.

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

3条回答
时光不老,我们不散
2楼-- · 2020-06-23 07:26

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);
查看更多
男人必须洒脱
3楼-- · 2020-06-23 07:33

This works:

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

function get() {
 var content = $('#example').text(); 
 alert(content);
}
查看更多
Summer. ? 凉城
4楼-- · 2020-06-23 07:38

Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.

查看更多
登录 后发表回答