You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为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>

关键说明

  1. 批量事件绑定:用querySelectorAll一次性选中所有目标链接,循环绑定监听器,比逐个写onclick更简洁易维护
  2. 异步逻辑优化:改用async/await让异步代码逻辑更直观,替代原来的链式then写法
  3. 跨域错误处理:在catch块中通过window.open打开原链接,noopener参数可防止新窗口对当前页面的恶意操作,符合安全规范
  4. 兼容性:fetch和async/await支持所有现代浏览器,若需兼容极旧浏览器(如IE),可替换为XMLHttpRequest实现

内容的提问来源于stack exchange,提问作者clp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:34:52