<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.active {
background-color: chocolate;
}
</style>
</head>
<body>
<script>
let xhr = new XMLHttpRequest()
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos")
xhr.send()
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState == 4 && /^20\d$/.test(xhr.status)) {
let res = xhr.responseText //获取到的是一个字符串
// 转为数组 计算总个数
let count = JSON.parse(res).length
// 设置一个每页显示的个数
const page = 15
// 求页数fanyinhao
const pageCount = Math.ceil(count / page)
changePage(1)
function changePage(currentPage) {
let xhr = new XMLHttpRequest()
xhr.open("GET",
`https://jsonplaceholder.typicode.com/todos?_page=${currentPage}&_limit=${page}`)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && /^20\d$/.test(xhr.status)) {
// 7、在监听方法中获取对应相应的内容
let res = xhr.responseText
// res拿到的是string 转化为数组
res = JSON.parse(res)
// 8、渲染页面
// 创建table
if (document.querySelector('table')) {
document.querySelector('table').remove()
}
// 添加头部栏
let table = document.createElement('table')
let thList = document.createElement('tr')
let th = document.createElement('th')
th.innerText = "序号"
thList.appendChild(th)
for (let key in res[0]) {
let th = document.createElement('th')
th.innerText = key
thList.appendChild(th)
}
table.appendChild(thList)
table.border = '1px'
// 将table添加到body
document.body.appendChild(table)
// 拿到的数据是一个数组 遍历对象数组
res.forEach((v, index) => {
// 创建tr和td
let tr = document.createElement('tr')
// 加序号
let firstTd = document.createElement('td')
// 填充内容
firstTd.innerText = index + 1
tr.appendChild(firstTd)
for (let attr in v) {
let td = document.createElement("td")
// 填充内容
td.innerText = v[attr]
tr.appendChild(td)
}
// 添加到table
table.appendChild(tr)
});
}
}
}
// 生成对应的切换按钮
for (let i = 0; i <= pageCount + 1; i++) {
// console.log(btns)
let btn = document.createElement('button')
btn.innerText = i
//切换按钮功能
btn.onclick = function () {
fn()
changePage(i)
btn.className = "active"
}
if (i == 1) {
btn.className = "active"
} else if (i == 0) {
btn.innerText = 'prev'
btn.onclick = function () {
let index = Number(document.querySelector('.active').innerText)
fn()
if (index > 1) {
index--
changePage(index)
}
btns[index].className = 'active'
}
} else if (i == pageCount + 1) {
btn.innerText = 'next'
btn.onclick = function () {
let index = Number(document.querySelector('.active').innerText)
fn()
if (index < pageCount) {
index++
// console.log(index, pageCount + 1)
changePage(index)
}
btns[index].className = 'active'
}
}
document.body.appendChild(btn)
}
let btns = document.querySelectorAll('button')
console.log(btns.length)
function fn(){
for (let i = 0; i < btns.length; i++) {
btns[i].className = ''
}
}
}
})
</script>
</body>
</html>