zoukankan      html  css  js  c++  java
  • 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>
    
    
  • 相关阅读:
    传球游戏(NOIP2008 普及组第三题)
    立体图(NOIP2008 普及组第四题)
    多项式输出(NOIP2009 普及组第一题)
    分数线划定(NOIP2009 普及组第二题)
    第5到8章
    第四章总结
    实验九
    实验五
    实验四
    实验三
  • 原文地址:https://www.cnblogs.com/xujinglog/p/14676542.html
Copyright © 2011-2022 走看看