简体   繁体   English

JavaScript分页问题

[英]Javascript Pagination Issue

I'm trying to make a simple Javascript pagination function, but I'm having this issue where instead of iterating through the array, it keeps adding new list items to the innerhtml. 我正在尝试制作一个简单的Javascript分页功能,但是我遇到了这个问题,它不是在数组中进行迭代,而是一直在将新列表项添加到innerhtml中。

  • I have tried creating an element and appending it to the DOM. 我尝试创建一个元素并将其附加到DOM。
  • I have tried using if/else statements to display the list items I want. 我尝试使用if / else语句显示我想要的列表项。
<body>
    <div class='result'></div>
    <button class="add">+</button>
   <script src='pretty.js'></script>
</body>
let dogs =  [
    'goldendoodle',
    'poodle',
    'afghan hound',
    'golden retriever',
    'labrador',
    'chihuahua',
    'pitbull',
    'german shepherd',
    'greyhound',
    'bull terrier'
  ]
  let high = 1;
  let low = 0;
  let result = document.querySelector('.result');
  let add = document.querySelector('.add');
  function Pagination(low,high) {


    for(var i = 0 ; i < dogs.length;i++) {
        let answer = document.createElement('div');
        answer.classList.add('dogs-dom');

        answer.innerHTML = dogs[i];
        result.appendChild(answer);

        if(i >= low && i < high) {

                answer.style.display ='block';


        } 
        if(i < low || i > high) {

            answer.style.display ='none';
        }




    }

  }
  Pagination(low,high);
  add.addEventListener('click', () => {

      low += 2;
      high += 2;

    Pagination(low,high);
  });


When I click the button, I want the next two array items to appear and replace the last two shown. 当我单击按钮时,我希望接下来的两个数组项出现并替换显示的最后两个。

To use the approach you've outlined above you'll need to clear the innerHtml of the result element before appending new children. 要使用上面概述的方法,您需要在添加新的子级之前清除result元素的innerHtml At the top of your Pagination function try result.innerHtml = ''; Pagination功能的顶部尝试result.innerHtml = ''; .

That said if you are using a hide/show approach to paginate the list it would be more efficient to create the dom elements only once and modify the style.display property of each instead of clearing out the result and re-creating all of the answer div s on every click. 也就是说,如果您使用隐藏/显示方法对列表进行分页,则只创建一次dom元素并修改style.display属性(而不是清除result并重新创建所有answer每次点击div

Your Pagination function only adds elements to the dom each time it is called. 您的Pagination功能每次调用时只会向dom添加元素。

You can either remove the existing elements every time Pagination is called, and render only those that should be displayed, eg: 您可以在每次调用Pagination删除现有元素,并仅渲染应显示的元素,例如:

function Pagination(low,high) {
  result.innerHTML = ''; // remove all children of result

  // only render the children which should be visible
  for(var i = low ; i < high;i++) {
    let answer = document.createElement('div');
    answer.classList.add('dogs-dom');
    answer.innerHTML = dogs[i];
    result.appendChild(answer);
  }
}

Or you can use display: block; 或者您可以使用display: block; / display: none . / display: none (Will not scale very well with large lists) (如果列表很大,缩放比例将不会很好)

function Pagination(low,high) {
  // only append all dogs once
  if(result.childElementCount === 0) {
    for(var i = 0; i < dogs.length;i++) {
      let answer = document.createElement('div');
      answer.classList.add('dogs-dom');
      answer.style.display ='none';
      answer.innerHTML = dogs[i];
      result.appendChild(answer);
    }
  }

  // toggle display: none / block for each element
  for(var i = 0; i < dogs.length;i++) {
    if(i >= low && i < high)
      answer.style.display ='block';
    else
      answer.style.display ='none';
  }
}

As a bonus, heres a reusable pagination class example: 作为奖励,这是一个可重用的分页类示例:

 function Pagination(container, items) { this.container = container; this.result = container.querySelector('.result'); this.prevBtn = container.querySelector('.prev'); this.nextBtn = container.querySelector('.next'); this.items = items; this.offset = 0; this.limit = 5; this.updateDom(); this.prevBtn.onclick = this.prevPage.bind(this); this.nextBtn.onclick = this.nextPage.bind(this); } Pagination.prototype.nextPage = function() { if((this.offset + this.limit) < this.items.length) this.offset += this.limit; this.updateDom(); }; Pagination.prototype.prevPage = function() { if(this.offset >= this.limit) this.offset -= this.limit; this.updateDom(); }; Pagination.prototype.updateDom = function() { this.result.innerHTML = ''; let stop = Math.min(this.offset + this.limit, this.items.length); for(let i = this.offset; i < stop; i++) { let el = document.createElement("div"); el.appendChild(document.createTextNode(this.items[i])); this.result.appendChild(el); } let hasPrev = this.offset > 0; if(hasPrev) this.prevBtn.classList.remove('hide'); else this.prevBtn.classList.add('hide'); let hasNext = (this.offset + this.limit) < this.items.length; if(hasNext) this.nextBtn.classList.remove('hide'); else this.nextBtn.classList.add('hide'); }; let items = []; for (let i = 1; i <= 50; i++) items.push(`Item ${i}`); let pagination = new Pagination(document.querySelector(".paginate"), items); // You can also programatically switch to the next / prev page: // pagination.nextPage(); // pagination.prevPage(); 
 .hide { visibility: hidden; } 
 <div class="paginate"> <div class="result"></div> <button class="prev">PREV</button> <button class="next">NEXT</button> </div> 

Maybe this is along the lines of what you want to do? 也许这是您想要做的事情?

It tracks only a globalIndex (which would be like like your 'low' variable). 它仅跟踪globalIndex (就像您的“低”变量一样)。

The showNextTwoItems function: showNextTwoItems函数:
- Notes the indexes where we should start and end -记下应该在哪里开始和结束的索引
- Clears the container div -清除容器div
- Enters a while loop that appends items and increments the current index -进入一个while循环,该循环附加各项并增加当前索引
- Updates the globalIndex when enough items have been added -当添加了足够的项目时更新globalIndex

 let dogs = [ 'goldendoodle', 'poodle', 'afghan hound', 'golden retriever', 'labrador', 'chihuahua', 'pitbull', 'german shepherd', 'greyhound', 'bull terrier' ], containerDiv = document.querySelector('.result'), addBtn = document.querySelector('.add'), globalIndex = 0; // Tracks where we left off (starts at zero) const NUMBER_TO_SHOW = 2; addBtn.addEventListener("click", showNextTwoItems); // Calls function on click function showNextTwoItems(){ let numberToShow = NUMBER_TO_SHOW, // In case we ever want to change numberToShow currentIndex = globalIndex, // Gets local copy of globalIndex (always < dogs.length) // Lets us stop looping when we've shown enough or reach the end of the array stopBeforeIndex = Math.min(currentIndex + numberToShow, dogs.length); containerDiv.innerHTML = ""; // Clears div while(currentIndex < stopBeforeIndex){ // Creates and appends a text node with the next dog const newItem = document.createTextNode(dogs[currentIndex]); containerDiv.appendChild(newItem); // Creates and appends a line break const lineBreak = document.createElement("BR"); containerDiv.appendChild(lineBreak); // Moves on to the next index currentIndex++; } // Updates global index (making sure it is not too big for the array) globalIndex = currentIndex < dogs.length ? currentIndex : 0; } 
 <button class="add">+</button> <div class='result'></div> 

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

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