js通过localstorage将所有商品遍历一遍,选出最近商品的浏览记录信息添加到个人中心的具体代码
时间: 2024-02-01 09:15:48 浏览: 29
首先,你需要将浏览记录信息存储到localStorage中。可以在每次用户访问商品详情页时,将当前商品的信息以一定的格式(如JSON)存储到localStorage中。可以使用以下代码:
```javascript
// 获取当前商品信息
var product = {
id: '123',
name: '商品名称',
price: 100,
// 其他属性
};
// 将商品信息存储到localStorage中
var history = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : [];
history.push(product);
localStorage.setItem('history', JSON.stringify(history));
```
然后,在个人中心页面,你需要从localStorage中获取最近的浏览记录信息。可以使用以下代码:
```javascript
// 从localStorage中获取浏览记录信息
var history = localStorage.getItem('history') ? JSON.parse(localStorage.getItem('history')) : [];
// 选出最近的商品
var latestProduct = history[0];
for (var i = 1; i < history.length; i++) {
if (history[i].lastVisited > latestProduct.lastVisited) {
latestProduct = history[i];
}
}
// 在页面中显示最近的商品信息
document.getElementById('latest-product').innerHTML = latestProduct.name;
```
这里假设每个商品对象都有一个名为`lastVisited`的属性,表示最近访问时间。你可以在记录商品信息时,将该属性设置为当前时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)