zoukankan      html  css  js  c++  java
  • js还原底层简单的history路由

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>history 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() {
                let {path,component} = comp[$(this).index()]
                history.pushState({id:0},'movie',path)
                render(component)
                // 拿到参数
                let state = history.state
                console.log(state);
            })
    
            function render(component){
                $('#content').html(component)
            }
    
            // 监听hash是否发生变化,截取变化的长度对比然后根据结果操控dom
            $(window).on('load',()=>{
                history.pushState({id:0},'movie111','/movie')
                render(comp[0].component)
            })
    
            // 只能检测到前进后退 
            $(window).on('popstate',()=>{
                // 拿到参数
                let state = history.state
                console.log(state);
                let pathname = location.pathname
                let {component} = comp.find(v=>v.path === pathname)
                render(component)
            })
        </script>
    </body>
    </html>
    
  • 相关阅读:
    初学移动专题
    IE下a标签跳转失败
    c++中一个多态的实例
    字符串中是否有相同的字符
    求乘积最大的连续子序列
    跳跃游戏
    求一个非负整数的平方根 二分法
    罗马数 与 整数 相互转换
    二进制相加
    链表分割
  • 原文地址:https://www.cnblogs.com/xujinglog/p/14677391.html
Copyright © 2011-2022 走看看