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>
    
  • 相关阅读:
    nodejs + mongodb
    实习踩坑
    jQuery获取点击对象的父级
    python正则表达式
    python文件基础IO,OS
    python模块
    python时间和日期
    python number
    python循环
    Vue2.0 【第一季】第6节 v-model指令
  • 原文地址:https://www.cnblogs.com/xujinglog/p/14677391.html
Copyright © 2011-2022 走看看