为listen类列表的href添加事件监听,实现文件替换及跨域处理
解决方案
核心实现逻辑
- 选中
.listen列表下的所有<a>标签,批量绑定点击事件监听器 - 点击时先阻止默认跳转行为,尝试通过
fetch加载目标文件内容 - 若加载失败(包括跨域错误),则触发默认行为,在新窗口打开链接
完整代码示例
<!DOCTYPE html> <html lang="en"> <meta charset="utf-8"> <title>Read file into div</title> <article> <h1>My HTML</h1> <ul class="listen"> <li><a class="loc" href="file1.html">Select file 1</a></li> <li><a class="loc" href="file2.htm">Select file 2</a></li> <li><a class="loc" href="file2.txt">Select file 3</a></li> <li><a href="https://example.com/">Load external file in new window with noopener</a></li> </ul> <h1>Please find selected content below:</h1> <div id="SelectedText"> <p>Replace me</p> </div> <script> // 获取目标容器和所有需要监听的链接 const contentContainer = document.getElementById('SelectedText'); const links = document.querySelectorAll('.listen a'); // 定义加载内容的函数 async function loadContent(url) { try { const response = await fetch(url); if (!response.ok) throw new Error(`请求失败: ${response.status}`); const content = await response.text(); contentContainer.innerHTML = content; } catch (err) { // 加载失败时,在新窗口打开原链接,添加noopener提升安全性 window.open(url, '_blank', 'noopener'); } } // 为每个链接绑定点击事件 links.forEach(link => { link.addEventListener('click', (e) => { e.preventDefault(); // 先阻止默认跳转 loadContent(link.href); }); }); </script> </article>
关键说明
- 批量事件绑定:用
querySelectorAll一次性选中所有目标链接,循环绑定监听器,比逐个写onclick更简洁易维护 - 异步逻辑优化:改用
async/await让异步代码逻辑更直观,替代原来的链式then写法 - 跨域错误处理:在
catch块中通过window.open打开原链接,noopener参数可防止新窗口对当前页面的恶意操作,符合安全规范 - 兼容性:
fetch和async/await支持所有现代浏览器,若需兼容极旧浏览器(如IE),可替换为XMLHttpRequest实现
内容的提问来源于stack exchange,提问作者clp
相关产品推荐
相关产品推荐

