html 跳转页面传参、点击获取DOM参数

时间:2022-06-25 08:55:18

虽然现在前端框架已经很多,尤其是几大流行框架,比如Vue,React,Angular 等,已经去DOM化,但是还是有很多公司仍在使用 HTML + CSS + JS 。

这里记载一下用到的HTML传参 问题。

一、页面之间传参:

HTML 页面跳转可以直接通过,给 href 赋值

       $(document).on('click', '.detail', function() {
window.location.href = 'scorePage.html'
})

? 传参

       $(document).on('click', '.detail', function() {
window.location.href = `scorePage.html?id=${id}&name=${name}`;
})

在新页面获取参数:

 let url = location.search;
console.log(url); // ?id=44&name=guozheng

获取的参数要转化成json格式:封装一个函数

 function getParams() {
let obj = new Object(); let url = location.search;
if(url.indexOf('?') != -1) {
let str = url.substr(1);
let arrs = str.split('&');
arrs.map(item => {
obj[item.split('=')[0]] = item.split('=')[1]
})
}
return obj;
}

这里返回的 obj 就是包含所有 参数的 一个对象。

二、获取 DOM 自定义的 属性值。

HTML 结构:

   <div class="box"></div>

js 代码:

这里模仿的是 后台获取数据 然后 拼接 DOM 结构,将数据已自定义属性的方式 绑定到 DOM上。

     let obj = {
name: 'guozheng',
id: 34,
age: 27,
sex: 'man'
} let info = JSON.stringify(obj); let str = `<div id="test" class="title-name" name='guo' data-info=${info}>法律价值度</div>` $('.box').append(str); $('#test').on('click', function() {
let info2 = $(this).attr('data-info');
console.log(JSON.parse(info2)); // {name: "guozheng", id: 34, age: 27, sex: "man"}
})