亲爱的老师,我来交作业了,麻烦您帮我检查一下呢!⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>二级菜单</title>
<style>
/* css reset */
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
/* menu */
.menu {
width: 1200px;
height: 50px;
line-height: 50px;
background-color: rgba(0, 0, 0, 0.1);
}
.menu-item {
position: relative;
cursor: pointer;
float: left;
margin: 0px;
padding: 0 20px;
}
.menu-content {
display: none;
position: absolute;
top: 50px;
left: 0px;
width: 100px;
height: 300px;
padding: 0 10px;
background-color: rgba(0, 0, 0, 0.1);
}
.menu-item:hover {
background-color: rgba(0, 0, 0, 0.4);
}
.menu-item:hover .menu-content {
display: block;
}
.menu-loading {
margin: 45px 0 0 92px;
}
</style>
</head>
<body>
<ul id="menu" class="menu"></ul>
<script type="module">
// 导入封装好的ajax
import { getJSON } from './ajax/index.js';
const menuURL = 'https://www.imooc.com/api/mall-PC/index/menu';
const menuEl = document.getElementById('menu');
// 调用getJSON并把url传进去
getJSON(menuURL)
// 成功的的时候,一级菜单
.then(repsonse => {
let html = '';
// 遍历返回来得到repsonse.data
for (const item of repsonse.data) {
// 把遍历出来的repsonse.data放进html中
html += `
<li class="menu-item" data-key="${item.key}">
<span>${item.title}</span>
<div class="menu-content">
<p><img class="menu-loading" src="./loading.gif" alt="加载中" /></p>
</div>
</li>
`;
}
menuEl.innerHTML = html;
})
// 成功的的时候,二级菜单
.then(() => {
const items = menuEl.querySelectorAll('.menu-item');
for (const item of items) {
// 给一级菜单绑定鼠标经过事件
item.addEventListener(
'mouseenter',
() => {
// 检测item.dataset.done是否存在,如果存在的话,就不需要重新请求获取了
if (item.dataset.done === 'done') return;
// item.dataset.done不存在的时候,那么第二次发送请求
getJSON(
// 因为二级菜单是根据一级菜单的key进行展示的,所以重新发送请求是,应该加上key值
// console.log(item.dataset.key, menuURL)
// `https://www.imooc.com/api/mall-PC/index/menu/${item.dataset.key}`
`${menuURL}/${item.dataset.key}`
)
// 二级获取成功的时候
.then(repsonse => {
// console.log(repsonse);
// 给item.dataset.done加上done,证明,已经加载过一遍了,就不用重新发送加载了
item.dataset.done = 'done';
let html = '';
// 遍历二级菜单的内容,并添加内容上去
for (const item of repsonse.data) {
html += `<p>${item.title}</p>`;
}
item.querySelector('.menu-content').innerHTML = html;
})
// 二级获取失败的时候
.catch(err => {
console.log(err);
});
},
false
);
}
})
.catch(err => { //失败的时候
console.log(err);
});
</script>
</body>
</html>
11
收起
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星