This one had me stymied for a bit as well. It turns out that IE does not allow the insertion of JS directly via innerHTML unless you include the 'defer' property (see the second link below). This property is unique to IE and apparently allows IE to defer execution of any JS until after the other markup has been loaded. A warning, though...if you include two script tags (as I did), there is no guarantee which one will execute first, as the scripts appear to be loaded asynchronously. This should only be a problem if your scripts are dependent on one another (as mine were).
There is an additional caveat as well...you must insert non-script markup at the same time that you insert the script. I was unable to insert the script tags by themselves, with or without the 'defer' property. Finally, the script tags must be placed after all other non-script markup being inserted. Otherwise, the script tags are stripped out of the inserted HTML.
Here are a few references:
MS innerHTML Reference:
http://msdn.microsoft.com/en-us/library/ms533897%28v=vs.85%29.aspx
MS Defer Property Reference:
http://msdn.microsoft.com/en-us/library/ms533719%28v=vs.85%29.aspx
Example of Script Insert via code (yes, it actually does work):
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/insertScript_2.htm
My Test Code:
// I downloaded the MS example file above and tweaked their script a bit,
// resulting in this. Using the proper approach to the defer property
// (namely: defer="defer") did not provide me with consistent results, so
// sticking with 'DEFER' may be necessary.
// Note: Try moving the 'sHTML' variable to the end of the script string.
function insertScript2()
{
var sHTML="<input type=button onclick=" + "go2()" + " value='Click Me'><BR>";
var sScript = sHTML + "<SCRIPT DEFER type='text/javascript'> function go2(){ alert('Hello from inserted script.') } </SCRIPT" + ">";
ScriptDiv.innerHTML = sScript;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…