Symptom (s): When setting a value for an element's InnerHTML, if the provided HTML code contains a JS script, many times these scripts are invalid or valid on some browser, but are not valid on other browsers.
Reason: Different browsers have different ways of handling scripts that are inserted into InnerHTML. After practice, summed up as follows:
For IE, first, the script tag must take the defer attribute, and secondly, the InnerHTML node must be in the DOM tree at the time of insertion.
For Firefox and Opera, InnerHTML's owning node cannot be in the DOM tree at the time of insertion.
According to the above conclusion, the general method of setting InnerHTML is given:
Copy Code code as follows:
/*
* Description: Cross-browser settings InnerHTML method
* Allow inserted HTML code to contain script and style
Parameters
* El:dom the node in the tree, set its InnerHTML
* Htmlcode: Inserted HTML code
* Tested Browsers: ie5+, firefox1.5+, opera8.5+
*/
var set_innerhtml = function (el, Htmlcode)
{var ua = navigator.userAgent.toLowerCase ();
if (Ua.indexof (' msie ') >= 0 && ua.indexof (' opera ') < 0)
{Htmlcode = ' <div style= ' display:none ' >for ie</div> ' + htmlcode;
Htmlcode = Htmlcode.replace (/<script ([^>]*) >/gi, ' <script$1 defer= ' true ' > ');
el.innerhtml = Htmlcode;
El.removechild (El.firstchild);
}
Else
{var el_next = el.nextsibling;
var el_parent = El.parentnode;
El_parent.removechild (EL);
el.innerhtml = Htmlcode;
if (El_next)
El_parent.insertbefore (el, El_next)
Else
El_parent.appendchild (EL);
}
}
The above code also has a problem: if the inserted HTML code contains the document.write statement, then the entire page is corrupted. In this case, you can avoid it by redefining document.write. The code is as follows:
Copy Code code as follows:
/*
Description: Redefine the document.write function.
Avoid document.write statements in HTML code that is inserted when using set_innerhtml, causing the original page to be corrupted.
*/
document.write = function () {
var BODY = document.getelementsbytagname (' body ') [0];
for (var i = 0; i < arguments.length; i++) {
argument = Arguments[i];
if (typeof argument = = ' String ') {
var el = body.appendchild (document.createelement (' div '));
Set_innerhtml (el, argument)
}
}
}