为什么在进行新查询后,prevButton 和 nextButton 会从过去的查询中删除?

问题描述 投票:0回答:1

从某种意义上来说,这是聊天框应用程序。一旦进行新查询,我的 prevButton 和 nextButton 就会从过去的查询中删除,因此分页仅适用于当前查询,但我希望能够引用过去的查询,而不必再次询问查询才能使用分页

let page = 1;
let allResults = JSON.parse('{{ result|tojson|safe }}');
let itemsPerPage = 1;
var queryId = 0;
let queryState = null;

// Retrieve the existing data
let storedData = sessionStorage.getItem('resultsHistory');

// If there's no existing data, create a new object
// Otherwise, parse the existing data
let resultsHistory = storedData ? JSON.parse(storedData) : {};

window.onload = function() {
  var container = document.querySelector('.container');
  container.scrollTop = container.scrollHeight;

  fetchData();

}

function renderState(queryState) {
  // Check if the state object exists
  if (queryState) {
    // Render the state
    console.log('Query state')
    console.log(resultsHistory);
  } else {
    console.error('No state found for queryId: ' + queryId);
  }
}

function fetchData() {
  // Get the queryId from localStorage
  queryId = localStorage.getItem('queryId');
  if (queryId === null) {
    queryId = 0;
  } else {
    queryId = parseInt(queryId);
  }

  queryId++;
  console.log('Current queryId: ' + queryId);

  // Save the queryId to localStorage
  localStorage.setItem('queryId', queryId.toString());
  let data = allResults.slice()
  queryState = {
    total_pages: Math.ceil(data.length / itemsPerPage),
    current_page: 1,
    results: data,
    queryId: queryId
  };

  resultsHistory[queryId] = queryState;
  console.log(resultsHistory[queryId]);

  // Store the updated history
  sessionStorage.setItem('resultsHistory', JSON.stringify(resultsHistory));

  var queryDiv = document.querySelector('.query');
  if (!queryDiv) {
    // If no 'queryDiv' exists, create a new one
    queryDiv = document.createElement('div');
    queryDiv.className = 'query';
    queryDiv.id = 'query' + queryId;
    document.querySelector('.container').appendChild(queryDiv);
  }

  // Check if a 'buttonsContainer' already exists
  var buttonsContainer = document.querySelector('.buttonsContainer');
  if (!buttonsContainer) {
    // If no 'buttonsContainer' exists, create a new one
    buttonsContainer = document.createElement('div');
    buttonsContainer.className = 'buttonsContainer';
    document.querySelector('.container').appendChild(buttonsContainer);
  }

  // Create a new 'buttonsDiv' for this query
  var buttonsDiv = document.createElement('div');
  buttonsDiv.className = 'buttons';
  buttonsDiv.id = 'buttons' + queryId;
  buttonsDiv.dataset.queryId = queryId; // Store the queryId as a data attribute
  buttonsContainer.appendChild(buttonsDiv);

  // Create the previous and next buttons for this query
  let prevButton = document.createElement('button');
  prevButton.id = 'prevButton' + queryId;
  prevButton.textContent = 'Previous';
  buttonsDiv.appendChild(prevButton);

  let nextButton = document.createElement('button');
  nextButton.id = 'nextButton' + queryId;
  nextButton.textContent = 'Next';
  buttonsDiv.appendChild(nextButton);

  fetchPage(queryId, 1);
  addPaginationEventListeners(queryId, prevButton, nextButton, buttonsDiv);
  // generatePaginationButtons(queryId, queryState);
}


function addPaginationEventListeners(queryId, prevButton, nextButton, buttonsDiv) {
  prevButton.addEventListener('click', function() {
    var queryId = this.parentElement.dataset.queryId;
    if (resultsHistory[queryId].current_page > 1) {
      resultsHistory[queryId].current_page--;
      fetchPage(queryId, resultsHistory[queryId].current_page);
      renderState(resultsHistory[queryId]);
    }
  });

  nextButton.addEventListener('click', function() {
    var queryId = this.parentElement.dataset.queryId;
    if (resultsHistory[queryId].current_page < resultsHistory[queryId].total_pages) {
      resultsHistory[queryId].current_page++;
      fetchPage(queryId, resultsHistory[queryId].current_page);
      renderState(resultsHistory[queryId]);
    }
  });
}

function fetchPage(queryId, pageNumber) {
  let start = (pageNumber - 1) * itemsPerPage;
  let end = start + itemsPerPage;
  let data = resultsHistory[queryId].results.slice(start, end);

  // Update the current page number
  resultsHistory[queryId].current_page = pageNumber;

  populateTable(data);
}

function populateTable(data) {
  let tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
  tableBody.innerHTML = '';

  for (let item of data) {
    for (let [key, value] of item) {
      let row = document.createElement('tr');
      let cellKey = document.createElement('td');
      let cellValue = document.createElement('td');
      cellKey.textContent = key;
      cellValue.textContent = value;
      row.appendChild(cellKey);
      row.appendChild(cellValue);
      tableBody.appendChild(row);
    }
  }
}
<div class="common-buttons-container"></div>

我为每个查询创建了一组具有唯一 id 的新按钮,并将它们附加到该查询的特定“queryDiv”

javascript html dom setstate
1个回答
0
投票

我对您的代码进行了一些调整,包括添加一些模拟数据以及对 populateTable 函数迭代已解析项目的方式进行调整。根据我的测试,这些更改似乎是有效的,并且您想要的功能似乎按预期工作。

但是,我注意到当前的代码结构可以改进,以获得更好的可维护性和可扩展性。虽然普通 JavaScript 功能强大,但对于复杂的应用程序,您可能会发现探索现代框架或库是有益的。采用此类技术可以增强项目的结构,促进更轻松的维护,并有可能提高性能。此建议旨在指导您实现 Web 开发的最佳实践,尽管工具的选择最终取决于您项目的具体要求以及您的个人或团队偏好。

如果您还有任何疑问或需要进一步澄清我所做的更改,请随时询问!

模拟数据:

let allResults = [];
for (let i = 1; i <= 100; i++) {
    allResults.push({
        id: i,
        name: `Item ${i}`,
        description: `Description of item ${i}`
    });
}

新的 populateTable 函数:

function populateTable(data) {
  let tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
  tableBody.innerHTML = '';

  data.forEach(item => {
    // Iterate over the properties from the received object
    Object.entries(item).forEach(([key, value]) => {
      let row = document.createElement('tr');
      let cellKey = document.createElement('td');
      let cellValue = document.createElement('td');
      cellKey.textContent = key;
      cellValue.textContent = value;
      row.appendChild(cellKey);
      row.appendChild(cellValue);
      tableBody.appendChild(row);
    });
  });
}

更新代码

© www.soinside.com 2019 - 2024. All rights reserved.