jq点击按钮添加、删除localstory的数组

$(function() { 
   var array = [].concat(JSON.parse(localStorage.getItem('history'))); //定义空数组
    //提交按钮点击事件 并刷新页面
    $('#submitBtn').click(function() {
                array.push(plate); //添加到数组中
                localStorage.setItem('history', JSON.stringify(array_unique(array))); //存 去重
                if (array.length >= 7) {
                    array.shift()
                    localStorage.setItem('history', JSON.stringify(array)); //
                } //限制存储个数 
              location.reload(true); 
        })
  //去重
    function array_unique(arr) {
        return arr.filter(function(e, i) {
            return arr.indexOf(e) === i;
        })
    }
    //清空历史数据
    var ondata = JSON.parse(localStorage.getItem('history'))
    $(".clearHistory").click(function() {
            ondata.splice(0, ondata.length);
            localStorage.setItem('history', JSON.stringify(ondata)); //
            location.reload(true);
        })
     //html历史展示
    if (JSON.parse(localStorage.getItem('history')) == null) {
        console.log('暂无历史记录')
    } else {
        var data= JSON.parse(localStorage.getItem('history'))
        if (data[0] == null) {
            data.splice(jQuery.inArray(null, data), 1); //去除null
        }
        for (var i = 0; i < data.length; i++) {
            $('#history').append('<span id="delplate">' + data[i] + '</span>')
        }
        $("span").click(function() {
            console.log(data[$(this).index()])//获取jqhtml的span下标
        })
    }
})

 

posted @ 2020-07-01 08:50  茗涵  阅读(402)  评论(0编辑  收藏  举报