源代码:
下载代码
AI 编程工具
点击运行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <style> .myClass { color: white; background-color: DodgerBlue; padding: 20px; text-align: center; margin: 10px; } </style> <h1>template 元素</h1> <p>实例中数组的每一项使用一个新的 div 元素填充网页。</p> <p>每个 div 元素的 HTML 代码都在模板元素内。</p> <p>点击按钮显示 template 元素中的隐藏内容。</p> <button onclick="showContent()">显示隐藏内容</button> <template> <div class="myClass">我喜欢: </div> </template> <script> var myArr = ["Google", "Runoob", "Taobao", "Wiki", "Zhihu", "Baidu"]; function showContent() { var temp, item, a, i; temp = document.getElementsByTagName("template")[0]; item = temp.content.querySelector("div"); for (i = 0; i < myArr.length; i++) { a = document.importNode(item, true); a.textContent += myArr[i]; document.body.appendChild(a); } } </script> </body> </html>
运行结果: