跨页面传参

251 阅读1分钟

创建两个页面
index.html
a.html

index.html ↓↓↓

    <h1>
        首页
    </h1>
    <button class="btn">提交</button>
    <a href="./a.html?name=memeflyfly&age=22">提交</a>
    var as = {
        a: 'Ava',
        b: 'Bella',
        c: 'Carol',
        d: 'Diana',
        e: 'Elieen'
    }
    
    //为按钮绑定点击事件,跳转时传入参数
    document.querySelector('.btn').onclick = function () {
        window.location.href = `./a.html?a=${as.a}&b=${as.b}&c=${as.c}&d=${as.d}&e=${as.e}`
    }

a.html ↓↓↓

    <h1>
        a页面
    </h1>
    var str = window.location.search
    var res = str.substr(1)
    // console.log(res);

    //封装一个函数来转换拿到的参数
    function getSearch() {
        var arr = res.split('&')
        // console.log(arr);
        var obj = {}
        for (var i = 0; i < arr.length; i++) {
            var arr1 = arr[i].split('=')
            // console.log(arr1);
            obj[arr1[0]] = arr1[1]
        }
        return obj
    }

    console.log(getSearch(res));

image.png

使用a标签也可以传参 但是不能使用模板字符串,比较僵硬