# 迷你导航笔记--3
# hashMap
hashMap是一个数组,新增网站就是在hashMap内新增对象
const $lastLi = $('.siteList').find('li.last')
const hashMap = [
{logo:'V', url:"https://vuejs.org"},
{logo:'F', url:"https://fanison.xyz"}
];
const render = ()=>{
//移除之前的,重新渲染,否则会重复
$('.siteList').find('li:not(.last)').remove()
hashMap.forEach(node =>{
const $li = $(`<li>
<a href="${node.url}">
<div class="site">
<div class="logo">${node.logo}</div>
<div class="link">${node.url}</div>
</div>
</a>
</li>`).insertBefore($lastLi)
})
}
render()
# 使用render重写addButton点击事件
$('.addButton').on('click',()=>{
let url = window.prompt('请输入要添加的网址:')
if(url.indexOf('https') !== 0){
url = 'https://' + url
}
hashMap.push({
logo:url[8],
url:url
});
render()
});
# 添加缓存
在用户离开时将数据添加到缓存
//当窗口即将被卸载(关闭)时,会触发该事件
window.onbeforeunload = ()=>{
// 对象变成字符串
const string = JSON.stringify(hashMap)
localStorage.setItem('x',string)
}
# hashMap设置初始值
const x = localStorage.getItem('x')
const xObject = JSON.parse(x)
const hashMap = xObject || [
{logo:'V', url:"https://vuejs.org"},
{logo:'F', url:"https://fanison.xyz"}
];
# 简化Url
const simplifyUrl = (url)=>{
return url.replace('https://','').replace('http://','').replace('www.','').replace(/\/.*/,'')
//删除https、http、www开头及 / 结尾的内容
}
hashMap.forEach(node =>{
const $li = $(`<li>
<a href="${node.url}">
<div class="link">${simplifyUrl(node.url)}</div>
</a>
</li>`).insertBefore($lastLi)
})
# logo大写
使用js或css控制
$('.addButton').on('click',()=>{
hashMap.push({
logo:simplifyUrl(url)[0].toUpperCase()
});
});
.siteList .site > .logo{
text-transform: uppercase;
}