我在角度2中创建了一个从html字符串转换为Documents片段的函数:
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:对象不支持属性或方法' getElementById'。 我调查了它,似乎template.content是未定义的。是否有解决方法使其在IE11中也能正常工作?谢谢!
答案 0 :(得分:0)
您可以使用多种 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;
}