模拟单页面应用程序(SPA)

a标签的锚点值是用来实现:页面内部跳转
  • 1 ajax
  • 2 哈希值(锚点)的使用(window.location.hash #)
  • 3 hashchange 事件
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        div {
            height: 500px;
            width: 100%;
            background-color: hotpink;
        }
    </style>
</head>

<body>
    <ul>
        <li>
            <a href="#/find">发现音乐</a>
        </li>
        <li>
            <a href="#/my">我的音乐</a>
        </li>
        <li>
            <a href="#/friend">朋友</a>
        </li>
    </ul>

    <div id="content">
        <!-- 这是内容区域 -->
    </div>

    <script src="./node_modules/axios/dist/axios.js"></script>
    <script type="text/javascript">
        // 进入页面,就触发这个函数来获取当前哈希值对应的内容
        handlerChange()

        window.addEventListener('hashchange', handlerChange)

        function handlerChange() {
            // console.log('哈希值改变了', location.hash)
            switch (location.hash) {
                case '#/friend':
                    axios.get('./friend.json').then(res => {
                        console.log(res)
                        document.getElementById('content').innerHTML = `<h1>${res.data.content}</h1><p>${res.data.name}</p>`
                    })
                    break;

                case '#/my':
                    axios.get('./my.json').then(res => {
                        console.log(res)
                        document.getElementById('content').innerHTML = `<h1>${res.data.content}</h1><p>${res.data.name}</p>`
                    })
                    break;

                case '#/find':
                    axios.get('./find.json').then(res => {
                        console.log(res)
                        document.getElementById('content').innerHTML = `<h1>${res.data.content}</h1><p>${res.data.name}</p>`
                    })
                    break;
            }
        }
    </script>
</body>

</html>

转载于:https://www.cnblogs.com/mushitianya/p/10529119.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值