多级导航很常见,平常网购的时候会选择地址,选择省份→选择城市→选择区/县,那如何利用jQuery实现多级导航呢?
1.Html,结构永远最重要
<div id="nav">
<div class="province">
<span>江苏省</span>
<ul class="city">
<li>
<span>南京市</span>
<ul class="district">
<li>秦淮区</li>
<li>玄武区</li>
</ul>
</li>
<li>
<span>常州市</span>
</li>
</ul>
</div>
<div class="province">
<span>安徽</span>
<ul class="city">
<li>
<span>合肥</span>
<ul class="district">
<li>蜀山区</li>
<li>宾湖区</li>
</ul>
</li>
<li>
<span>芜湖市</span>
</li>
</ul>
</div>
</div>
2.CSS样式
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
span {
display: block;
}
#nav {
width: 150px;
border: 1px solid #ccc;
text-align: center;
line-height: 28px;
font-size: 14px;
cursor: pointer;
}
.province {
background-color: rgb(5, 38, 48);
color: white;
}
.city {
display: none;
background-color: rgb(9, 66, 83);
}
.city>li {
position: relative;
}
.district {
width: 150px;
background-color: rgb(14, 92, 116);
position: absolute;
left: 150px;
top: 0;
display: none;
}
</style>
3.js实现
//引入jQuery
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script><script>
//引入JSON文件
$.get('./citys.json', function(ps) {
//循环省份数组
ps.forEach(p => {
let province = $('<div class="province" />')
let p_span = $('<span/>') //省份
p_span.text(p.name) //省份名等于数据库的name
province.append(p_span) //省份加到div中
let city = $('<ul class="city">') //创建城市
province.append(city) //城市加到div
$('#nav').append(province) //省份加到大盒子
//循环每个省对应的城市数组
p.citys.forEach(c => {
let c_li = $('<li/>') //每个城市创建一个li
let c_span = $('<span/>') //该sapn显示城市的名称
let d_ul = $('<ul class="district">') //该ul显示城市对应的所有区县
c_span.text(c.name)
c_li.append(c_span)
c_li.append(d_ul)
city.append(c_li)
//循环每个城市对应的区县
c.district.forEach(d => {
let d_li = $('<li/>')
d_li.text(d.name)
d_ul.append(d_li)
})
})
})
// 两个方法放到异步Ajax中 保持同步
//省份导航点击事件
$('.province>span').click(function() {
$(this).parent().children('.city').slideToggle()
})
//城市导航点击事件
$('.city>li>span').click(function() {
$(this).parent().children('.district').toggle()
})
})
</script>