history对象,当前url添加参数且不刷新页面


这周突然想起来在url路径后面添加参数且不刷新页面的知识点,我好像之前都没注意到,突然想看看,所以看的时候就看了history对象。

History对象提供了对浏览器的会话历史的访问,允许在用户浏览历史中向前向后跳转,同时——从HTML5开始提供了对history栈中内容的操作。

1.window.history.back()
window.history.back()

在history中向后跳转,和用户点击浏览器的回退按钮效果相同

2.window.history.forward()
window.history.forward()

在history中向前跳转,和用户点击浏览器的前进按钮

3.window.history.go() 跳转到history中的指定的点

通过与当前页面相对位置来标志(当前页面的相对位置标志为0)

window.history.go(-1) //向前移动了一个页面,相当于window.history.back()
window.history.go(1) //向前移动了一个页面,相当于window.history.forward()

所以,可以传递参数为2,并向前移动2个页面。(可以通过window.history.length来查看历史堆栈中页面的数量)

4.添加和修改历史记录中的数目

html5中引入了history.pushState()history.replaceState()方法,分别可以添加和修改历史记录条目

4.1 pushState()

当前页面原本是http://127.0.0.1:5500/test.html

history.pushState({
    
     page: 1 }, 'title 1', '?page=1')

操作后变为http://127.0.0.1:5500/test.html?page=1

这个操作之后会添加浏览器历史记录。页面可以回退。

4.2 replaceState()

这个操作同上,操作之后不添加浏览器历史记录,页面不能回退。

5.实现js更改url参数,但不刷新或重载页面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #change {
    
    
        width: 20px;
        height: 20px;
        background-color: aquamarine;
    }
    #change2 {
    
    
        width: 20px;
        height: 20px;
        background-color: rgb(146, 127, 255);
    }
    #change1 {
    
    
        width: 20px;
        height: 20px;
        background-color: rgb(255, 255, 127);
    }
</style>

<body>
    <div id="change" onclick="updateUrl('number','2') "></div>
    <div id="change2" onclick="updateUrl('number1','2') "></div>
    <div id="change1" onclick="updateUrl('number1','3') "></div>
</body>
<script type="text/javascript">
    function updateUrl(key, value) {
    
    
        var newurl = updateNewUrl(key, value)
        //向当前url添加参数,有历史记录
        window.history.pushState({
    
    
            path: newurl
        }, '', newurl);

        // 向当前url添加参数,没有历史记录
        // window.history.replaceState()({
    
    
        //     path: newurl
        // }, '', newurl);
    }

    function updateNewUrl(key, value) {
    
    
        var uri = window.location.href
        if (!value) {
    
    
            return uri;
        }
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
    
    
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        }
        else {
    
    
            return uri + separator + key + "=" + value;
        }
    }
</script>

</html>

猜你喜欢

转载自blog.csdn.net/m0_64562972/article/details/130035561