Forum Moderators: open
...
<hr>
<span id="test"></span>
<hr>
...
document.getElementById('test').innerHTML="Hello JS";
My question is, how to insert another javascript code to above html page and run it. For example, the following code is my first try, which does not work:(
var myjs = "<script>alert('hello js');</script>";
document.getElementById('test').innerHTML=myjs;
I don't think it will be possible to do exactly what you are asking by working with nodes either. Scripts are loaded and executed when the page loads, with the exception that functions are run when called by an event.
Why not just write whatever HTML you want with innerHTML then, in the same script, execute whatever JavaScript you want executed?
var myjs = "<script>alert('hello js');</script>";
document.getElementById('test').innerHTML=myjs;
The way you have it written is the way you would write the javascript into a new document, such as might be done in a popup or iframe. When attaching some javascript to an element on an existing document, you don't need the <script> tags.
Try:
var myjs = 'alert(\'hello js\')';
document.getElementById('test').onmouseover=new Function(myjs);
Here is a full html page that sets a onmouseover and onclick. Hopefully this will get you pointed in the right direction:
<html>
<head>
<title>Test</title>
<script language="javascript">
<!--
var oldmouse;
var oldclick;
function tst()
{
document.getElementById('test').onclick=new Function('alert(\'hello js 2\')');
document.getElementById('test').onmouseover=oldmouse;
}
//-->
</script>
</head><body>
<hr>
<span id="test">sdfasdfasdfasdfaf</span>
<hr><form>
<input type="button" value="test1 - set onmouseover" onClick="var myjs='alert(\'hello js 1\')';document.getElementById('test').onmouseover=new Function(myjs);document.getElementById('test').onclick=oldclick;" />
<input type="button" value="test2 - set onclick" onClick="tst()" />
</form></body>
<script language="javascript">
oldmouse=document.getElementById('test').onmouseover;
oldclick=document.getElementById('test').onclick;
</script>
</html>