打开链接而不重新加载页面

问题描述 投票:0回答:3

当我单击链接时,我希望 page2.html 出现,而无需重新加载当前页面。尽管进行了所有尝试,当我单击链接时,它确实会在显示 page2.html 之前重新加载整个页面

<script>
  $(document).ready(function() {
    $("a").click(function(event) {
      var $this = $(this),
        url = $this.data("url");

      $(document.body).load(url);
      event.preventDefault();
    });
  }); < /script>

主页.html

<a href="#" data-url="page2.html" class="topic-list-item">

  <h3 class="topic-title">Internet Protocol Basics</h3>

  <div class="topic-description-text">
    Learn how Internet Protocol is used
  </div>
</a>

ajax
3个回答
0
投票

设置流进度条

<div class="progress-bar-container">
  <div class="progress-bar"></div>
</div>

实现 JavaScript 路由:

document.addEventListener("DOMContentLoaded", function () {
  const progressBar = document.getElementById("progress-bar");
  // Update the progress bar width based on the loading percentage
  function updateProgressBar(percentage) {
    progressBar.style.width = `${percentage}%`;
    progressBar.classList.add("filled");
    // hide progress bar when content is loaded
    if (percentage == 100) {
      setTimeout(() => {
        progressBar.classList.remove("filled");
        progressBar.style.width = 0;
      }, 300);
    }
  }
  // Fetch content based on the URL and update the page
  function fetchContent(url) {
    updateProgressBar(0); // Reset progress bar
    console.log(url);
    fetch(url, {
      headers: {
        "Content-Type": "text/html; charset=utf-8",
      },
      mode: "cors",
    })
      .then((response) => {
        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        const total = +response.headers.get("Content-Length");
        let loaded = 0;
        let html = "";
        function read() {
          reader.read().then(({ done, value }) => {
            if (done) {
              const parser = new DOMParser();
              const doc = parser.parseFromString(html, "text/html");
              // Extract the specific HTML element and their child's from the parsed document
              const primary = doc.querySelector("#primary");
              // take content element from current page
              const appContainer = document.getElementById("content");
              // Then, Remove all child elements
              while (appContainer.firstChild) {
                appContainer.removeChild(appContainer.firstChild);
              }
              // Append a new element
              appContainer.appendChild(primary);
              updateProgressBar(100); // Set progress bar to 100% when content is loaded
              return;
            }
            loaded += value.length;
            updateProgressBar((loaded / total) * 100);
            const chunk = decoder.decode(value, { stream: true });
            html += chunk;
            // Process the content here if needed
            // somthing like pelase wait or spinner..
            read(); // Continue reading the stream
          });
        }
        read();
      })
      .catch((error) => {
        console.error(error);
        updateProgressBar(0); // Reset progress bar in case of errors
      });
  }
  // Handle link clicks
  function handleLinkClick(event) {
    const target = event.target;
    // Check if the clicked element or its parent is an anchor element
    const anchor = target.closest("a");
    if (anchor) {
      event.preventDefault();
      // Get the href attribute of the anchor element
      const targetUrl = anchor.getAttribute("href");
      // Update the URL and push a new history state
      history.pushState(null, "", targetUrl);
      // Fetch and load the content for the clicked link
      fetchContent(targetUrl);
    }
  }
  // Attach click event listeners to all links
  const allLinks = document.querySelectorAll("a");
  allLinks.forEach((link) => {
    link.addEventListener("click", handleLinkClick);
  });
  // Handle the popstate event to update the page when the user navigates back/forward
  window.addEventListener("popstate", () => {
    fetchContent(window.location.href);
  });
});

在上面的代码中,我们首先将一个事件侦听器附加到

DOMContentLoaded
事件,以确保我们的 JavaScript 代码在页面加载完成时运行。

handleLinkClick
函数负责拦截链接点击,防止默认行为,启动进度条动画,并使用
fetchContent
函数获取点击链接的内容。

fetchContent
函数向目标 URL 发送 GET 请求,以文本形式检索响应,停止进度条动画,并使用获取的 HTML 更新内容容器。

确保有一个链接到 HTML 的 CSS 文件,您可以在其中定义进度条动画的样式。这是进度条的基本 CSS 示例:

.progress-bar-container {
  width: 100%;
  height: 2px;
  background-color: transparent;
  position: absolute;
  top: 0;
  display: block;
}

.progress-bar {
  width: 0;
  height: 100%;
  background-color: #f00;
  position: relative;
  transition: width 0.3s ease-in-out;
  opacity: 0;
}
.progress-bar.filled {
  opacity: 1;
}
/* Optional: Add animation to the progress bar */
@keyframes progress-animation {
  0% {
    width: 0;
  }
  100% {
    width: 100%;
  }
}

随意自定义 CSS 样式以匹配您网站的设计。


-1
投票
$("a").click(function() {
var $this = $(this),
    href = $this.attr("href");

$(document.body).load(href);

location.href = "#" + href;
});

请参阅 jQuery.fn.load 了解更多详细信息。


-1
投票

尝试这个代码它会工作

$(document).ready(function () {
            $("a").click(function (event) {
                var $this = $(this),
                    url = $this.data("url");

                $(document.body).load(url);
                event.preventDefault();
            });
        });

Digital 代码的问题是,当我们点击时,他也没有使用数据函数来获取 url,然后将调用锚点的默认操作,因此我们需要停止默认操作,所以我使用了 event.preventDefault();

也始终将 jquery 代码放在 $(document).ready 块之间

© www.soinside.com 2019 - 2024. All rights reserved.