如何为不同的页面使用相同的脚本文件?

问题描述

您好,我是新的网络开发人员,正在从事报价网站项目。

现在要理解我的问题,请看下面的 Javascript。

const resultEl = document.querySelector('.allquotes');
const pageSize = document.querySelector('select[name="page-size"]');
const pageCurr = document.querySelector('input[name="page-curr"]')
const resultCount = document.querySelector('.result-count')
const pageNoCurr = document.querySelector('.page-no-curr');
const pageNoCount = document.querySelector('.page-no-count')
const btnFirst = document.querySelector('.page-btn-first');
const btnPrev = document.querySelector('.page-btn-prev');
const btnNext = document.querySelector('.page-btn-next');
const btnLast = document.querySelector('.page-btn-last');

let results = [];

const getResultCount = () => results.length;
const getPageSize = () => +pageSize.value;
const getCurrPage = () => +pageCurr.value;
const getPageCount = () => Math.ceil(getResultCount() / getPageSize());

const pageResponse = (records,pageSize,page) =>
  (start => records.slice(start,Math.min(records.length,start + pageSize)))
  (pageSize * (page - 1));

const main = async() => {
  btnFirst.addEventListener('click',navFirst);
  btnPrev.addEventListener('click',navPrev);
  btnNext.addEventListener('click',navNext);
  btnLast.addEventListener('click',navLast);
  pageSize.addEventListener('change',changeCount);

  results = await retrieveAllQuotes();
  updatePager(results);
  redraw();
};
const redraw = () => {
  resultEl.innerHTML = '';
  const paged = pageResponse(results,getPageSize(),getCurrPage());
  const contents = document.createElement('div');
  contents.classList.add("allStatus");
  const quotes = paged.map((record) => `<div class='latestatus'><p class='copytxt'>${record.quotes}</p><div> <button class="copystatus btn">copy</button><span class="status-copy-alert hidden" id="status-copy-alert">copied!</span></div></div>`);
  const quoteGroupNumer = Math.ceil(quotes.length / 2);
  const groups = Array(quoteGroupNumer).fill('').map((value,index) => {
    const groupQuoteFirst = quotes[2 * index]; // 0,2,4,6
    const groupQuoteSecond = quotes[2 * index + 1] || ''; // 1,3,5,7

    return `<div class="flex">${groupQuoteFirst}${groupQuoteSecond}</div>`;
  });

  contents.innerHTML = groups.join('');
  resultEl.append(contents);
};
const navFirst = (e) => {
  pageNoCurr.textContent = 1;
  pageCurr.value = 1;
  redraw();
}

const navPrev = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const prevPage = curr > 1 ? curr - 1 : curr;
  pageCurr.value = prevPage;
  pageNoCurr.textContent = prevPage;
  redraw();
}

const navNext = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const nextPage = curr < pages ? curr + 1 : curr;
  pageCurr.value = nextPage;
  pageNoCurr.textContent = nextPage;
  redraw();
}

const navLast = (e) => {
  pageNoCurr.textContent = getPageCount();
  pageCurr.value = getPageCount();
  redraw();
}

const changeCount = () => {
  updatePager();
  redraw();
};

const updatePager = () => {
  const count = getPageCount();
  const curr = getCurrPage();
  pageCurr.value = curr > count ? 1 : curr;
  pageNoCurr.textContent = curr > count ? 1 : curr;
  pageNoCount.textContent = count;
  resultCount.textContent = getResultCount();
};

const retrieveAllQuotes = async function() {
  // here we are making a network call to your api
  const response = await fetch('https://goodman456.000webhostapp.com/api.PHP');
  
  // then converting it to json instead of a readable stream
  const data = await response.json();

  return data;
}
document.querySelector('.allquotes').addEventListener(

  'click',function (e) {

    e.preventDefault();
    

    if (e.target && e.target.matches('.copystatus')) {

        const quote = e.target.parentNode.closest('.latestatus')

            .childNodes[0].textContent;
      
      const notify = e.target.nextSibling.closest('.status-copy-alert');
      
      notify.classList.toggle('hidden');
      setTimeout(() => {
  notify.classList.add('hidden');
},600);

        const textArea = document.createElement('textarea');

        textArea.value = quote;

        document.body.appendChild(textArea);

        textArea.select();

        document.execCommand('copy');

        textArea.remove();

    }

  },false

);
main();

注意 JavaScript 中的这一部分

const retrieveAllQuotes = async function() {
  // here we are making a network call to your api
  const response = await fetch('https://goodman456.000webhostapp.com/api.PHP');
  
  // then converting it to json instead of a readable stream
  const data = await response.json();

  return data;
}

我使用 API 来获取报价。

现在考虑我们有 3 个 html 页面,分别是 hp.html、lo.html 和 tr.html。现在 hp.html 是快乐语录,lo.html 是爱情语录,tr.html 是趋势语录。

现在我需要对这 3 个页面使用上面的 Javascript。如您所知,这些是不同的类别。有什么方法可以让我对所有 3 个页面使用相同的脚本文件(因为存储问题)并且只更改不同页面的 API 链接。换句话说,我对所有页面使用相同的脚本,但 API 部分将被更改。那么有什么方法可以让我使用相同的脚本并且只更改 API 部分。

我尝试了很多方法解决这个问题,但都没有奏效。作为 Javascript 的新手,我对此知之甚少。

非常感谢回答这个问题的人。

解决方法

每页在 window 对象上设置一个变量或使用 var 在全局范围内声明它。这将允许其他脚本访问设置值,因为它们现在是全局的。

在每个页面上更改此属性或变量的值以获取连接到页面的数据。

<html>
  <head>
    <title>Page</title>
  </head>
  <body>
    <script>
      window.__api__ = 'https://goodman456.000webhostapp.com/api.php';
    </script>
    <script src="script.js"></script>
  </body>
</html>

然后在 API 脚本中使用此全局值作为端点以与 fetch 一起使用。

const retrieveAllQuotes = async function() {
  const response = await fetch(window.__api__);  
  const data = await response.json();
  return data;
}

__ 命名空间是为了确保变量名称很少有机会被未来的浏览器更新覆盖。

,

我没有足够的“声誉”来评论,但我给你一个想法,例如使用 if 条件检查 URL 例如。

if((window.location.herf).indexOf("lo.html") > -1 ){
//To your love API
const response = await fetch('https://goodman456.000webhostapp.com/api.php');
}
else if((window.location.herf).indexOf("hp.html") > -1 ){
//To your desired API and so on

const response = await fetch('https://goodman456.000webhostapp.com/api.php');

}

谢谢。