javascript七基础学习系列三千零七十三:使用<template>标签

注意,在前面的例子中,DocumentFragment 的所有子节点都高效地转移到了foo 元素上,转移
之后DocumentFragment 变空了。同样的过程也可以使用标签重现:
const fooElement = document.querySelector(‘#foo’);
const barTemplate = document.querySelector(‘#bar’);
const barFragment = barTemplate.content;
console.log(document.body.innerHTML);
//


//

//
//


//


//


//
fooElement.appendChild(barFragment);
console.log(document.body.innerHTML);
//

//


//


//


//

//
如果想要复制模板,可以使用importNode()方法克隆DocumentFragment:
const fooElement = document.querySelector(‘#foo’);
const barTemplate = document.querySelector(‘#bar’);
const barFragment = barTemplate.content;
console.log(document.body.innerHTML);
//

//

//
//


//


//


//
fooElement.appendChild(document.importNode(barFragment, true));
console.log(document.body.innerHTML);
//

//


//


//


//

//
//


//


//


//
模板脚本
脚本执行可以推迟到将DocumentFragment 的内容实际添加到DOM 树。下面的例子演示了这个
过程:
// 页面HTML:
//
//

//
//
//
const fooElement = document.querySelector(‘#foo’);
const barTemplate = document.querySelector(‘#bar’);
const barFragment = barTemplate.content;
console.log(‘About to add template’);
fooElement.appendChild(barFragment);
console.log(‘Added template’);
// About to add template
// Template script executed
// Added template
如果新添加的元素需要进行某些初始化,这种延迟执行是有用的。

猜你喜欢

转载自blog.csdn.net/m0_68635815/article/details/143498945