我在angular 2中创建了一个将html字符串转换为文档片段的函数:
private htmlToElement(html): DocumentFragment {
let template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content;
}它适用于Chrome和Firefox,但对于IE11,抛出以下错误错误TypeError: Object不支持属性或方法'getElementById‘。我调查了一下,template.content似乎是未定义的。有没有办法让它在IE11中也能工作?谢谢!
发布于 2021-03-22 21:55:39
您可以使用许多polyfill选项中的一个,最小的解决方案可以是https://www.npmjs.com/package/template-polyfill或更复杂的实现https://github.com/webcomponents/polyfills/blob/master/packages/template/template.js
或者你可以使用下面的代码,它肯定更长,不完整,但也不是很慢,原理应该能帮助你解决问题:
/**
* Convert string to html
*
* @param {string} str - HTML source string
* @param {boolean} multiple - Contains multiple nodes, default: true
*
* @return {null|HTMLElement|NodeList} - Element or collection of elements
*/
export function str2node( str, multiple = true ) {
str = str.trim();
if ( !str.length ) {
return null;
}
/**
* Best practice should be the following, once IE11 support dies, or when using a polyfill
*/
let template = document.createElement( 'template' );
if ( 'content' in template ) {
template.innerHTML = str;
if ( multiple ) {
return template.content.childNodes;
}
return template.content.firstChild;
}
// fix for IE11, with slow detection using div or correct parent element if required
// TODO: check for other special cases with elements requiring a specific parent?
// like: source [ audio video picture ], area [ map ], caption [ table ], option [ select],
// td > tr > table tbody tfoot thead, dt dd > dl
template = document.createElement( str.substr( 0, 4 ) === '<li ' ? 'ul' : 'div' );
template.innerHTML = str;
if ( multiple ) {
return template.childNodes;
}
return template.firstChild;
}https://stackoverflow.com/questions/48991350
复制相似问题