本文介绍如何使用现代 JavaScript(Fetch API)实现点击链接后异步加载外部 HTML 文件,并将其内容注入指定 <div> 容器,避免直接执行 JS 文件,确保安全、可维护且符合语义化规范。
本文介绍如何使用现代 javascript(fetch api)实现点击链接后异步加载外部 html 文件,并将其内容注入指定 `
` 容器,避免直接执行 js 文件,确保安全、可维护且符合语义化规范。在 Web 开发中,常需按需加载结构化内容(如表格、表单或组件片段),而非一次性渲染全部 HTML。但需注意:直接“加载并执行 JS 文件”存在严重安全隐患(如 XSS)且违背语义——<a onclick="getScript('Orange.js')"> 实际意图并非运行脚本,而是展示对应内容。正确做法是将数据/模板分离为静态 HTML 片段(如 Orange.html),再通过 fetch() 获取并安全注入 DOM。
<a href="#" class="load-table-link" data-file="./Orange.html" data-destination="myTableResult">Orange</a><div id="myTableResult"></div>
⚠️ 注意:href="#" 需配合 e.preventDefault() 阻止默认跳转;data-* 属性解耦逻辑与结构,支持多链接复用。
// 封装通用加载函数const addFileToDestination = (file, destinationId) => { fetch(file) .then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`); return response.text(); }) .then(html => { const container = document.getElementById(destinationId); if (!container) throw new Error(`Target element #${destinationId} not found`); // 使用 <template> 或 createElement + innerHTML(确保内容解析) const fragment = document.createElement('div'); fragment.innerHTML = html; container.appendChild(fragment); }) .catch(err => { console.error('Failed to load content:', err); document.getElementById(destinationId).innerHTML = `<em>加载失败:${err.message}</em>`; });};// 绑定所有触发链接document.querySelectorAll('.load-table-link').forEach(link => { link.addEventListener('click', e => { e.preventDefault(); const file = link.dataset.file; const dest = link.dataset.destination; if (file && dest) addFileToDestination(file, dest); });});
<table border="1" class="data-table"> <thead> <tr><th>品种</th><th>甜度(10分制)</th><th>直径(cm)</th></tr> </thead> <tbody> <tr><td>Valencia</td><td>9</td><td>8</td></tr> <tr><td>Jaffa</td><td>10</td><td>7</td></tr> </tbody></table>
此方案兼顾安全性、可维护性与扩展性——只需新增带 data-file 和 data-destination 的链接,即可复用同一套逻辑加载任意 HTML 片段,是现代前端动态内容注入的标准实践。