目录
项目包搭建
node环境管理
- npm init -y
- npm i 模块名称
项目包目录结构
- common:公共自定义JS
- assets:存放资源,图片,视频,音频
- utils:工具包 - 第三方的脚本
- pages:页面
- components:组件页面
- index.html:入口
pages
index.html
<!DOCTYPE html>
<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" />
<link rel="stylesheet" href="./common/css/reset.css" />
<link rel="stylesheet" href="./common/css/base.css" />
<link rel="stylesheet" href="./common/css/global.css" />
<link rel="shortcut icon" href="./assets/img/favicon.ico" type="image/x-icon">
<title>美食广场</title>
</head>
<body>
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
<script src="./utils/jquery-3.6.1.min.js"></script>
<script src="./common/js/common.js"></script>
<script>
$("#header").load("./components/header/header.html")
$("#footer").load("./components/footer/footer.html")
// 获取路径参数
const path = $.s("path", "home")
const p = `./pages/${path}/${path}.html`
$("#body").load(p)
// 动态加载样式
$("head").append(
`<link rel="stylesheet" href="./pages/${path}/css/index.css">`
)
const script = document.createElement("script")
script.src = `./pages/${path}/js/index.js`
$('body').append(script)
</script>
</body>
</html>
page.js
$(function () {
// 封装url
function getData(param) {
var url = `https://douyu.xin88.top/api/room/list?page=${param}&`
$.get(url, function (el) {
// 滚动条置顶
$(window).scrollTop(0)
$(".list").html(
el.data.list.map(value => {
const { roomName, nickname,hn,roomSrc, title, pic, views } = value
return `
<li>
<div class="flex f-c">
<img src="${roomSrc}" alt="" />
<span>${hn}</span>
<span>${nickname}</span>
</div>
<div>${roomName}</div>
</li>
`
})
)
$(".pager>ul").empty()
// 分页
// 当前页,总页数
const { nowPage, pageCount } = el.data
let start = nowPage - 2
// 最小为1
start = Math.max(start, 1)
let end = start + 4
end = Math.min(end, pageCount)
// 防止极限值,右侧极限值,反算左侧起始值
start = end - 4
start = Math.max(start, 1)
for (let i = start; i <= end; i++) {
$(".pager>ul").append(
`<li class="${i == nowPage ? "active" : ""}">${i}</li>`
)
}
console.log(el)
const prevBtn = $(".pager>button").first()
const nextBtn = $(".pager>button").last()
nowPage == 1 ? prevBtn.hide() : prevBtn.show()
nowPage == pageCount ? nextBtn.hide() : nextBtn.show()
})
}
getData(1)
// 动态新增子元素,事件委托
$(".pager>ul").on("click", "li", function () {
const param = $(this).text()
getData(param)
})
// 下一页
$(".pager>button")
.last()
.on("click", function () {
const param = $(".pager>ul>li.active").next().text()
const next_page = $(this).next()
getData(param)
})
// 上一页
$(".pager>button")
.first()
.on("click", function () {
const param = $(".pager>ul>li.active").prev().text()
const next_page = $(this).next()
getData(param)
if (param == 1) $(".pager>button").first().hide()
console.log(param)
})
})