最近写项目时使用到了本地存储的问题下面就是在项目中的真实使用情况:
通过window.localStorage.setItem(‘命名’,存储的内容)
$(".show-book").on("click", function() {
var headerurl = $(this).children(".fl").children("img").attr("src");
var bookname = $(this).children('.show-cont').children('h2').text();
var zname = $(this).children('.show-cont').children('p').children("span").text();
var booktxt = $(this).children('.show-cont').children('div').children("span").text();
window.localStorage.setItem('headerurl', headerurl);
window.localStorage.setItem('bookname', bookname);
window.localStorage.setItem('zname', zname);
window.localStorage.setItem('booktxt', booktxt);
window.location.href = 'buy.html';
})
然后再另外的一个页面通过window.localStorage.getItem(‘headerurl’)来获取存储的值
var headerurl=window.localStorage.getItem('headerurl');
var bookname=window.localStorage.getItem('bookname');
var zname=window.localStorage.getItem('zname');
var booktxt=window.localStorage.getItem('booktxt');
var htmls=`<div class="buy-book">
<img src="${headerurl}" alt="" />
</div>
<div class="buy-title">
<h4>${bookname}</h4>
</div>
<div class="buy-author">
作者:<span>${zname}</span>
</div>
<div class="buy-border"></div>
<div class="buy-brief">
${booktxt}
</div>
<div class="buy-btn">
点击购买
</div>`
$('.buy-cont').append(htmls)