简体   繁体   English

根据条件重置计数器变量

[英]Reset counter variable on condition

I have this simple "pagination" counter which is fetching the next page from an API. 我有一个简单的“分页”计数器,该计数器可从API获取下一页。 It works fine but the problem is that whenever I change category (movies or series) the counter obviously doesn't reset so instead of fetching the first page of the new category it continues from the number it left off. 它可以正常工作,但问题是,每当我更改类别(电影或系列)时,计数器显然都不会重置,因此与其获取新类别的第一页,它还是从其保留的编号开始继续。

I tried numerous conditional combinations but nothing really worked so far. 我尝试了多种条件组合,但到目前为止,什么都没有奏效。 I'm sure it's not that hard to solve I just can't think of the right logic to use. 我确信解决起来并不难,只是我想不出要使用的正确逻辑。

let page = 1; 
document.getElementById('load-more').addEventListener('click', () => {
    page++;

    const movies = document.getElementById('movies');
    const series = document.getElementById('series');


    if(movies.classList.contains('active-link')) {

        getMovies(page);


    } else if (series.classList.contains('active-link')) {

        getSeries(page);

    }
})

Reseting the let counter inside the if..else doesn't really work because every time I click the load more button it resets it back to page 1. 在if..else内重置let计数器并不能真正起作用,因为每次我单击“加载更多”按钮时,它将重置为第1页。

Use separate variables for the current movies page and the current series page. 对当前电影页面和当前系列页面使用单独的变量。 Also note that you can simplify your logic by using a single querySelector instead of selections followed by classList.contains : 还要注意,您可以通过使用单个querySelector而不是后跟classList.contains的选择来简化逻辑:

let moviesPage = 1;
let seriesPage = 1;
document.getElementById('load-more').addEventListener('click', () => {
  if (document.querySelector('#movies.active-link')) {
    moviesPage++;
    getMovies(moviesPage);
  } else if (document.querySelector('#series.active-link')) {
    seriesPage++;
    getSeries(seriesPage);
  }
});

Set another event listener for the click on your #movies and #series link, 为您的#movies和#series链接上的点击设置另一个事件侦听器,

and set the page variable to 1 at this place. 并将page变量设置为1。

That would be the usual behavior when switching lists, one usually see a reset of paging. 这是切换列表时的通常行为,通常会看到页面调度的重置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM