Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
57 views
in Technique[技术] by (71.8m points)

javascript - How to use same script file for different pages?

Hey am new web developer and am working on a quote website project.

Now to understand my question, Just see the below 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();

And notice this section in 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;
}

I use API to fetch the Quotes.

Now consider that we have 3 html pages namely hp.html, lo.html and tr.html . Now the hp.html is for happy quotes and lo.html is for love quotes and tr.html for trend quotes.

Now I need to use the above Javascript to these 3 pages. As you know these are different category. Is there any way so that I can use same script file for all the 3 pages (Because of storage problem) and only change the API links of different pages. In other words, I use same script for all pages but the API section will be changed. So is there any way so that I can use the same script and only change the API section.

I have tried many ways to solve this problem but none of them work. As am new to Javascript I don't know much about this.

I hartley thanks for those who answer this question.

question from:https://stackoverflow.com/questions/65872021/how-to-use-same-script-file-for-different-pages

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I doesn't have enough "reputation" to comment but I am giving you an idea that make that such as for checking URL using if conditions For example.

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');

}

Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...