我想要实现的目标:

  • 为withhrefs中的所有项添加事件监听器listclass="listen"
  • 当用户点击任何列表项时,用所选文件的内容替换div其内容。id="SelectedText"
<!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><a class="loc" href="file2.htm">Select file 2</a>
      <li><a class="loc" href="file2.txt">Select file 3</a>
      <li><a        href="https://example.com/">Load external file in new window with noopener</a>
    </ul>
    <h1>Please find selected content below:</h1>
    <div id = "SelectedText">
      <p>Replace me
    </div>
    <script> magic here </script>
  </article>
<!-- Local file -->
<p>file i contains for example:
<h1>Ipsum dolor sit amet</h1>

我试过:

<!DOCTYPE html>
<html lang="nl">
<meta charset="utf-8">
<title>Test</title>
  <nav>
    <ul>
      <li><a href="#" onclick="loadDoc('/nieuws.htm'); return false;">Nieuws</a>
      <li><a href="#" onclick="loadDoc('/teams/teams.htm'); return false;">Teams</a>
      <li><a href="#" onclick="loadDoc('/links/links.htm'); return false;">Links</a>
    </ul>
  </nav>
  <main id="content">
  <p>Replace me
  </main>

使用 JavaScript 函数:

    <script>
    // Load external HTML document in div.
    function loadDoc(x) {
      fetch(x)
      .then((result) => {
        if (result.status != 200) { throw new Error("Bad Server Response"); }
        return result.text();
      })
      .then((content) => {
        document.getElementById("content").innerHTML = content;
      })
      .catch((error) => { console.log(error); });
    }
    </script>

但我发现使用事件处理程序的解决方案更加优雅。

更新当出现“Access-Control-Allow-Origin”错误时如何在新窗口中打开文件。

注意:在捕获(err)之后,我想执行默认行为,例如在单独的窗口(_blank)中加载文件。不知道该怎么做。

10

  • 1
    这个元素在哪里document.getElementById("content")


    – 

  • 1
    当你尝试时发生了什么addEventListener


    – 

  • 1
    <p>Replace me是无效标记


    – 

  • 1
    file1.htmfile1.html


    – 


  • 1
    @Roko C.Buljan<p>Replace me 已被 W3C 标记验证服务接受。


    – 


最佳答案
2

基于此关于

  • 使用
  • 使用addEventListener内联 JS 代替onclick
  • 用于event.preventDefault()防止默认浏览器行为(跟随锚点)

page1.html在项目根目录中包含如下 HTML 部分内容:

页面N.html

<h1>This is page N</h1>

这将是你的主页:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Read file into div</title>
</head>

<body>
    <h1>My HTML</h1>
    <ul class="listen">
        <li><a href="file1.html" class="loc">Load file 1</a>
        <li><a href="file2.html" class="loc">Load file 2</a>
        <li><a href="file3.html" class="loc">Load file 3</a>
    </ul>
    <h1>Please find selected content below:</h1>
    <div id="SelectedText">
        <p>Replace me</p>
    </div>
    <script>
        const loadPartial = async (elAnchor, elTarget) => {
            const file = elAnchor.getAttribute("href");
            try {
                const res = await fetch(file);
                const html = await res.text();
                const domp = new DOMParser();
                const doc = domp.parseFromString(html, "text/html");
                elTarget.innerHTML = ""; // clear old content
                elTarget.append(doc.documentElement);
            } catch (err) {
                console.error(err);
                open(file, "_blank", "noopener,noreferrer");
            };
        };


        const elTarget = document.querySelector("#SelectedText");
        const elListen = document.querySelector(".listen");

        elListen.addEventListener("click", (evt) => {
            const elAnchor = evt.target.closest(".loc");
            if (!elAnchor) return;
            evt.preventDefault(); // Prevent browser following the anchor
            loadPartial(elAnchor, elTarget);
        });
    </script>
</body>
</html>

我使用 DOMParser 将元素注入到您的页面中作为安全措施(XSS漏洞)。如果您信任插入的内容,则可以在try块内使用这个更简单(且更快)的解决方案:

const res = await fetch(file);
const html = await res.text();
elTarget.innerHTML = html;

提示:

需要动态(AJAX)将部分内容填充/提取到其页面中的开发人员经常会忘记,随着页面内容发生巨大且有意义的变化,访问者需要向后/向前导航历史记录、添加书签或分享当前页面内容的直接链接。使用上述方法是不可能的,因此我建议探索 – 即 pushState、popState 和 replaceState 方法来实现单页应用程序路由。

4

  • 确实运行良好。但是,如何处理 CORS 错误。我已将外部文件添加到我的问题中。


    – 

  • 如何将 href 限制为具有“loc”类的锚点?


    – 

  • @clp 更新了答案,使用 来打开一个新选项卡window.open()(您还必须移出const filetry块)。关于您的另一个问题,它也很简单……class="loc"在 HTML 中添加到锚点,然后在 JS 中添加,而不是const elAnchor = evt.target.closest("a");使用const elAnchor = evt.target.closest(".loc");


    – 


  • 这可能需要单独提出一个问题。但是如何忽略特定错误?例如,读取 .css 文件时发生的解析错误。


    – 

您的 loadDoc 函数没有执行任何操作。您需要使用 x 作为 url 来使用 fetch。

fetch(x).then(

1

  • 我所举的例子确实太过简单了。


    –