【问题标题】:How to use same script file for different pages?如何为不同的页面使用相同的脚本文件?
【发布时间】:2021-04-28 12:08:35
【问题描述】:

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

现在要理解我的问题,请看下面的 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 新手,我对此了解不多。

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

【问题讨论】:

  • 在此处发送参数const retrieveAllQuotes = async function(quoteType),您的 api 链接将根据 quoteType 参数更改,并从您的 html 中调用它,例如 - onClick(retrieveAllQuotes('loveQuote'))
  • 您使用网络服务器吗?如果有,是哪一个?你的服务器语言是什么?即使没有网络服务器,这个问题也可以解决,但如果有网络服务器会更优雅。

标签: javascript html scripting dynamic-html


【解决方案1】:

我没有足够的“声誉”来发表评论,但我给你一个想法,例如使用 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');

}

谢谢。

【讨论】:

    【解决方案2】:

    每页在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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 2022-01-20
      • 2016-07-13
      • 1970-01-01
      • 2012-01-02
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      相关资源
      最近更新 更多