Symptom: When setting a value for an element's innerHTML, if the provided HTML code contains js scripts, many times these scripts are invalid, or are valid on some browser, but not on other browsers.
Cause: Different browsers have different ways of handling scripts inserted into innerHTML. After practice, it is summarized as follows:
For IE, first, the script tag must have a defer attribute, and secondly, at the moment of insertion, the node to which innerHTML must be in the DOM tree.
For Firefox and Opera, the node to which innerHTML is not allowed to be in the DOM tree at the moment of insertion.
According to the above conclusion, a general method for setting innerHTML is given:
The code copy is as follows:
/*
* Description: Cross-browser setup innerHTML method
* Allows insertion of HTML code to include script and style
* Parameters:
* el: The node in the DOM 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);
}
}
There is another problem with the above code: if the inserted HTML code contains a document.write statement, it will destroy the entire page. For this case, it can be avoided by redefining document.write. The code is as follows:
The code copy is as follows:
/*
Description: Redefine the document.write function.
Avoid using set_innerHTML, inserting HTML code contains document.write statements, 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)
}
}
}