views:

1170

answers:

3

hello, here is my code:

<html>
<head>    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"&gt;&lt;/script&gt;    
</head>
<body>


<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

A: 

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.

Adam Bellaire
yes, but is it possible to insert javascript code into page with jquery, but not parsed ? i want to insert it like raw string or text.
mm
+1  A: 

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);
Danny
A: 

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);
}
fudgey