js还原底层简单的hash路由

hash虽然出现url中,但不会被包含在HTTP请求中,对后端完全没有影响,因此改变hash不会重新加载页面。hash 本来是拿来做页面定位的,如果拿来做路由的话,原来的锚点功能就不能用了。其次,hash的而传参是基于url的,如果要传递复杂的数据,会有体积的限制

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hash route</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.slim.js"></script>
</head>
<body>
    <ul>
        <li>电影</li>
        <li>影院</li>
    </ul>
    <div id='content'></div>
    
    <script>
        let comp = [
            {
                path:'/movie',
                component:'<div>comp1</div>'
            },
            {
                path:'/test',
                component:'<div>comp2</div>'
            }
        ]
        // 给li标签添加点击事件
        $('li').on('click',function() {
            console.log('1');
            location.hash = comp[$(this).index()].path
        })
        // 监听hash是否发生变化,截取变化的长度对比然后根据结果操控dom
        $(window).on('hashchange',()=>{
            let hash = location.hash.slice(1)
            $('#content').html(comp.filter(v=>v.path ===hash)[0]['component'])
        })
    </script>
</body>
</html>

posted @ 2021-04-19 14:00  xujing123  阅读(88)  评论(0编辑  收藏  举报