Home  >  Article  >  Web Front-end  >  innerHTML dynamically adds html code and scripts compatible with multiple browsers_javascript skills

innerHTML dynamically adds html code and scripts compatible with multiple browsers_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:34:181124browse

Symptom: When setting a value for innerHTML of an element, if the provided HTML code contains js scripts, many times these scripts are invalid, or they are valid on some browsers but not on other browsers.

Cause: Different browsers have different ways of handling scripts inserted into innerHTML. After practice, it can be summarized as follows:

For IE, first of all, the script tag must have the defer attribute, and secondly, at the time of insertion, the node to which innerHTML belongs must be in the DOM tree.

For Firefox and Opera, the node to which innerHTML belongs cannot be in the DOM tree at the time of insertion.

Based on the above conclusion, the general setting innerHTML method is given:

Copy code The code is as follows:

/*
* Description: Cross-browser setting innerHTML method
* Allow inserted HTML code containing script and style
* Parameter:
* el: 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 = '
for IE
' htmlCode;
htmlCode = htmlCode.replace(/]*)>/gi,'');
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. This situation can be avoided by redefining document.write. The code is as follows:
Copy code The code is as follows:

/*
Description: Redefine the document.write function.
Avoid when using set_innerHTML, the inserted HTML code contains the document.write statement, causing the original page to be damaged.
*/
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)
}
}
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn