Background
I want to dynamically put some javascript code in a DIV element using innerHTML. For this, I create a DIV object on my page and two buttons. First button, when pressed should insert some javascript code in the DIV element and the other function should utilize that code to execute some instructions.
Effort 1
I begin with this approach:
<html>
<head><title>Javascript Using innerHTML</title>
<script type="text/javascript">
var code="<script type='text/javascript'>\nfunction msgbox(msg){\nalert(msg);\n}\n</script>";
function setcode(obj) {
obj.innerHTML=code;
}
</script>
</head>
<body>
<div id="hello">
</div>
<button onclick='setcode(document.getElementById("hello"))'>SET</button>
<button onclick='msgbox("what up man?!");'>CHECK</button>
</body>
</html>
For reasons lame and unknown, I discover that using </script> in a javascript string immediately tends to close the <script> code, even when the thing is properly wrapped in quote marks.
Anyhow. I change the coding slightly so that </script> is formed by combining two strings and does not appear together.
Effort 2
<html>
<head><title>Javascript Using innerHTML</title>
<script type="text/javascript">
var xo="</";
var code="<script type=\"text/javascript\">\nfunction msgbox(msg){\nalert(msg);\n}\nmsgbox('aha!');\n"+xo+"script>";
function setcode(obj) {
obj.innerHTML=code;
}
</script>
</head>
<body>
<div id="hello">
</div>
<button onclick='setcode(document.getElementById("hello"))'>SET</button>
<button onclick='msgbox("what up man?!");'>CHECK</button>
</body>
</html>
The Problem
Even with the second effort, I still can't get the thing to work. After clicking the SET button, javascript code for defining msgbox() function should have been added to DIV's innerHTML and when CHECK button is pressed, that code should have worked and displayed a message on the screen.
But ... it does not.
WHYYYYYYYYYY???????!!!!!!!!