The article comes from a front-end program design course homework, the code is rough, big guy do not spray.
Requirement: achieve table paging
-
The number of records displayed on each page is specified by the user.
-
Refer to the following for style categories:
A total of () records, sub () page currently on () page;
Home page, previous page, next page, last page four buttons.
-
If the current page is greater than or equal to 3 or less than or equal to the last page -3, the current page is in the middle
-
Select the page to view through the drop-down menu to jump;
-
Use a text box to enter a page number to jump.
-
Set color for table header odd even pages
Effect:
HTML framework
The basic HTML is as follows
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Paging table demo</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<style>
.container {
margin-top: 30px;
}
.title {
margin-bottom: 30px;
color: # 333;
text-align: center;
}
.mr-3 {
margin-right: 20px;
}
.form-color {
height: 38px;
width: 40px;
}
</style>
</head>
<body>
<div class="container controller">
<h1 class="title">Paging table demo</h1>
<div id="allPut">
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">Number of lines per page:</span>
<input type="text" class="form-control" >
<button type="button" class="btn btn-primary mr-3" onclick="changeLine()">determine</button>
<span class="input-group-text" id="inputGroup-sizing-default">Please enter a header line color</span>
<input class="form-color mr-3" type="color" id="headColor">
<span class="input-group-text" id="inputGroup-sizing-default">Please enter odd line colors:</span>
<input class="form-color mr-3" type="color" id="oddColor">
<span class="input-group-text" id="inputGroup-sizing-default">Please enter even number line color:</span>
<input class="form-color mr-3" type="color" id="evenColor">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="inputGroup-sizing-default">Please enter page number:</span>
<input type="text" class="form-control">
<button type="button" class="btn btn-primary mr-3" onclick="changePage()">jump</button>
<span class="input-group-text" id="inputGroup-sizing-default">Please select page number</span>
<button type="button" class="btn btn-primary mr-3" onclick="selectPage()" id="button">jump</button>
</div>
</div>
</div>
<div class="container">
<table class="table table-striped" id="table">
<thead>
<tr>
<th scope="col">The serial number</th>
<th scope="col">The name</th>
<th scope="col">age</th>
<th scope="col">gender</th>
</tr>
</thead>
</table>
<nav id='nav'>
</nav>
</div>
<script src="./index.js"></script>
</body>
</html>
Copy the code
Implementation approach
This requirement can be divided into three categories
1. Color control
The color control code can be said to be relatively independent, just need to listen for the input color value, and change the table item color.
- Set the default color
let defaultColor = "# 333333";
Copy the code
- GetColor: Gets all the color information required for user input.
function getColor() {
let headColor = document.getElementById('headColor').value;
let oddColor = document.getElementById('oddColor').value;
let evenColor = document.getElementById('evenColor').value;
this.colors = [headColor, oddColor, evenColor];
}
Copy the code
- InitColor () : page table color initialization
function initColor() {
let headColor = document.getElementById('headColor')
let oddColor = document.getElementById('oddColor')
let evenColor = document.getElementById('evenColor')
let color = [headColor, oddColor, evenColor]
color.forEach((item) = > {
item.value = defaultColor
item.addEventListener("input", changeColor, false);
item.select()
})
}
Copy the code
- ChangeColor (Event) : Changes the table color
function changeColor(event) {
let color = event.target.value
let elem = []
switch (event.target.id) {
case 'headColor':
let thead = document.querySelector('.table>thead')
elem.push(thead)
break
case 'oddColor':
let oddtable = document.querySelectorAll('.table-striped>tbody>tr:nth-of-type(odd)')
elem = oddtable
break
case 'evenColor':
let eventable = document.querySelectorAll('.table-striped>tbody>tr:nth-of-type(even)')
elem = eventable
break
}
if (elem)
elem.forEach((item) = > {
item.style.backgroundColor = color
})
}
Copy the code
2. Data acquisition
A randomData() function is used to generate data for the convenience of the test, or to request data asynchronously
- randomData()
function randomData(number) {
function randomNum(minNum, maxNum) {
switch (arguments.length) {
case 1:
return parseInt(Math.random() * minNum + 1.10);
case 2:
return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
default:
return 0; }}let fristName = ['li'.'the king'.'张'.'赵'.'sun'.'zhu'.'liu'.'Chen'.'white'.'pay']
let lastName = ['golden flower'.'a Ming'.'mowgli'.'micro'.'the founding of the'.'British']
let gender = ['male'.'woman']
let data = []
for (let i = 0; i < number; i++) {
let index = i + 1
let name = `${fristName[randomNum(0, fristName.length - 1)]}${lastName[randomNum(0, lastName.length - 1)]}`
let age = randomNum(1.99)
let sex = gender[randomNum(0.1)]
data.push({ index, name, age, sex })
}
console.log(data)
return data
}
Copy the code
3. Paging lists
To focus on JavaScript logic, bootstarp.css is used on the page for the basic layout.
The front-end implementation idea of list paging is to capture the current page data and render dynamically during the rendering of each page. Every time the number of pages is changed, every time the number of pages is changed, the data is rerendered and the page is redrawn.
Data initialization
let num = prompt("How many pieces of data do I need to retrieve?"."100")
let data = randomData(num) // Get data
let page = 1 // The current number of pages
let line = 10 // Number of lines per page
let len = Math.ceil(data.length / line)/ / page number
Copy the code
Create a node
- CreateTable () : Creates a table
function createTable() {
let table = document.getElementById('table')
let tbody = document.createElement('tbody')
let tr, td;
let start = (page - 1) * line
let end = start + line
dataList = data.slice(start, end)
for (item in dataList) {
tr = document.createElement("tr");
for (Attribute in data[item]) {
td = document.createElement("td");
td.appendChild(document.createTextNode(dataList[item][Attribute]));
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody)
}
Copy the code
The key point is that start and end control what the page renders.
- CreateNavItem (className, text) : Creates a paging content item
function createNavItem(className, text) {
let span, li
span = document.createElement("span")
span.className = "page-link"
span.appendChild(document.createTextNode(text))
switch (text) {
case "Previous":
span.addEventListener('click'.() = > setPage(page - 1))
break
case "Next":
span.addEventListener('click'.() = > setPage(page + 1))
break
default:
span.addEventListener('click'.() = > setPage(text))
}
li = document.createElement("li")
li.className = className
li.appendChild(span)
return li
}
Copy the code
Used to create navigation bar forward and backward and page number, encapsulation to reduce code redundancy
- CreateNav () : Creates paging navigation
function createNav() {
let nav = document.getElementById('nav')
let span = document.createElement('span')
span.appendChild(document.createTextNode(` altogether${data.length}A record, points${len}Page is currently at number one${page}Page `))
nav.appendChild(span)
let ul = document.createElement('ul')
ul.className = "pagination justify-content-end"
let start = page > 3 ? page - 2 : 1
let end = page > len - 3 ? len + 1 : start + 5
if (page == 1)
className = "page-item disabled"
else
className = "page-item"
ul.appendChild(createNavItem(className, "Previous"))
for (i = start; i < end; i++) {
if (i == page)
className = "page-item active"
else
className = "page-item"
ul.appendChild(createNavItem(className, i))
}
if (page == len)
className = "page-item disabled"
else
className = "page-item"
ul.appendChild(createNavItem(className, "Next"))
nav.appendChild(ul)
}
Copy the code
The focus is on the classification and rendering of navigation items, the binding of different classes and events for different list items, and the control of the start and end pages, with five intervals from start to end, how to keep the current page centered in the middle range.
- CreateSelect () : Creates a page selection list
function createSelect() {
let div = document.querySelector("#allPut > div:nth-child(2)")
let button = document.querySelector("#button")
let select = document.createElement('select')
select.className = "form-select form-select-sm"
select.id = "select"
for (let i = 1; i < len + 1; i++) {
let option = document.createElement('option')
option.value = i
option.appendChild(document.createTextNode(i))
select.appendChild(option)
}
div.insertBefore(select, button)
}
Copy the code
Modify values (re-render)
- Set (modify) page and line, and start redrawing while changing values
function setPage(_page) {
page = _page
reRender()
}
function setLine(_line) {
line = _line
len = Math.ceil(data.length / line)
reRender()
}
Copy the code
- Button controlled binding function
function changeLine() {
_line = parseInt(document.querySelector("#allPut > div:nth-child(1) > input.form-control").value)
line = _line
if (_line <= data.length && _line > 0) {
setLine(parseInt(_line))
removeElem(document.querySelector('#allPut > div:nth-child(2) > select'))
createSelect()
}
else {
alert("Re-enter out of data range")}}function changePage() {
_page = parseInt(document.querySelector("#allPut > div:nth-child(2) > input").value)
if (_page <= len && _page > 0) {
setPage(_page)
}
else {
alert("Re-enter out of page range")}}function selectPage() {
let select = document.getElementById('select')
let index = select.selectedIndex
_page = parseInt(select.options[index].value)
if (_page <= len && _page > 0) {
setPage(_page)
}
else {
alert("Re-enter out of page range")}}Copy the code
Note the format of the form fetching data, as well as the form edge handling.
- Initialize redraw with utility functions
function removeElem(elem) {
let parent = elem.parentElement;
parent.removeChild(elem)
}
function initPage() {
initColor()
createTable()
createNav()
createSelect()
}
function reRender() {
removeElem(document.querySelector('table>tbody'))
removeElem(document.querySelector("#nav > span"))
removeElem(document.querySelector("#nav > ul"))
createTable()
createNav()
}
window.addEventListener("load", initPage, false);
Copy the code
The initialization function is triggered when the page load is loaded, and the page is redrawn when the data is updated.
conclusion
Codepen online sample
❤️ thank you
If you find this article helpful:
Click “like” to support it, so that more people can see this content.
We love the front end, we learn together and progress together.
If you feel good, you can also read other articles (thanks to friends for their encouragement and support 🌹🌹🌹) :
Make writing components document-free
Three sites play with the Grid layout
Nodejs implements timed crawlers
React-Query makes your state management more elegant
Front-end page layout learning magic tool
A copy of the interview essentials
Principle and implementation of SPA front-end routing
React Router principles and implementation