Javascript 使用本地存储和Jquery添加/删除多个产品的收藏夹

Javascript 使用本地存储和Jquery添加/删除多个产品的收藏夹,javascript,jquery,local-storage,Javascript,Jquery,Local Storage,我想集成一个系统来为产品添加书签。所有内容都存储在本地(Localstorage)。单击图标可将其放入收藏夹,再单击可将其删除。当产品不在收藏夹中时,心形图标为空;当产品在收藏夹中时,心形图标为满) 它在一个产品上运行得非常好。(如果访问者直接在产品页面上,这将是完美的) => $(文档).ready(函数(){ var existingEntries=JSON.parse(localStorage.getItem('products_fav'); 如果(existingEntries==nu

我想集成一个系统来为产品添加书签。所有内容都存储在本地(Localstorage)。单击图标可将其放入收藏夹,再单击可将其删除。当产品不在收藏夹中时,心形图标为空;当产品在收藏夹中时,心形图标为满)

它在一个产品上运行得非常好。(如果访问者直接在产品页面上,这将是完美的)

=>

$(文档).ready(函数(){
var existingEntries=JSON.parse(localStorage.getItem('products_fav');
如果(existingEntries==null)existingEntries=[];
var theIndex=-1;
对于(var i=0;i添加
var entryId=新搜索;
var entryTitle=标题;
var entrySlug=slug;
var entryImage=图像;
var entryBest_price=最佳价格;
var entryTotal_in_stock=总库存量;
变量日期=新日期();
date.setTime(date.getTime());
var date_product=date.togmString();
变量项={
“id”:entryId,
“标题”:入口标题,
“鼻涕虫”:入口鼻涕虫,
“图像”:入口图像,
“最佳价格”:入口最佳价格,
“库存总量”:入口库存总量,
“日期”:产品的日期
};
//将所有条目保存回本地存储
现有条目。推送(条目);
//按日期排序
var sortedExistingEntries=现有条目。排序(函数比较(a,b){
var dateA=新日期(a.Date);
var dateB=新日期(b.日期);
返回日期b-日期a;
});
//最多4种产品
if(Object.keys(sortedExistingEntries.length==5)sortedExistingEntries.pop();
//控制台.日志(分类识别入口);
setItem(名称,JSON.stringify(sortedExistingEntries));
}否则{
现有条目。拼接(“+theIndex+”,1);
setItem(名称,JSON.stringify(existingEntries));
}
}
}
i svg{
填充:透明;
行程:#f78554;
笔划宽度:1.5px;
转换:比例(1.2);
光标:指针;
}
i、 有源svg{
填充:#f78554;
}

JS-Bin

睡了一夜好觉后,我终于找到了解决办法

=>

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<i class="add_favorite"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="50" height="50">
    <path d="M21.317,3.761a5.581,5.581,0,0,0-8.14,0L12,4.994l-1.177-1.23a5.581,5.581,0,0,0-8.14,0,6.211,6.211,0,0,0,0,8.5L3.862,13.5v0L12,22h0l8.138-8.5v0l1.177-1.23A6.211,6.211,0,0,0,21.317,3.761Z" class="btn_toggle" data-id="317"></path>
</svg></i>
<br>
<i class="add_favorite"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="50" height="50">
    <path d="M21.317,3.761a5.581,5.581,0,0,0-8.14,0L12,4.994l-1.177-1.23a5.581,5.581,0,0,0-8.14,0,6.211,6.211,0,0,0,0,8.5L3.862,13.5v0L12,22h0l8.138-8.5v0l1.177-1.23A6.211,6.211,0,0,0,21.317,3.761Z" class="btn_toggle" data-id="318"></path>
</svg></i>
<br>
<i class="add_favorite"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="50" height="50" >
    <path d="M21.317,3.761a5.581,5.581,0,0,0-8.14,0L12,4.994l-1.177-1.23a5.581,5.581,0,0,0-8.14,0,6.211,6.211,0,0,0,0,8.5L3.862,13.5v0L12,22h0l8.138-8.5v0l1.177-1.23A6.211,6.211,0,0,0,21.317,3.761Z" class="btn_toggle" data-id="319"></path>
</svg></i>
</body>
</html>
JS


JS-Bin


i svg {
    fill: transparent;
    stroke: #f78554;
    stroke-width: 1.5px;
    transform: scale(1.2);
    cursor: pointer;
     transition: fill 1.5s,stroke 1s;
}
i.active svg {
    fill: #f6743c;
    transition: fill 1.5s,stroke 1s;
    stroke:#f6743c;
}
$(document).ready(function(){

    var existingEntries = JSON.parse(localStorage.getItem('products_fav'));
  if(existingEntries == null) existingEntries = [];

     $('[data-id]').each(function() {

       var dataId = $(this).data('id');
       var theIndex = -1;
        //var idProduct = $(this).attr("data-id");

       for (var i = 0; i < existingEntries.length; i++) { // search if product ID already in localstorage

        if (existingEntries[i].id == dataId) {
           theIndex = i;
           $(this).parents(".add_favorite").addClass("active");
           break;
         }
        }       


    })






  $(".btn_toggle").click(function(){
     $(this).parents(".add_favorite").toggleClass("active");

     var idProduct = $(this).attr("data-id");

     fav_local('products_fav',idProduct,'Apple iPhone 11 Pro (512 Go) - Gris Sidéral','apple-iphone-11-pro-gris-sideral-512-go-36156','https://boulanger.scene7.com/is/image/Boulanger/0190199391482_h_f_l_0','1559.00','11');

  });

});

function fav_local(name, new_search, title, slug, image, best_price, total_in_stock){

    if(window.localStorage!==undefined) {
        var existingEntries = JSON.parse(localStorage.getItem(name));
        if(existingEntries == null) existingEntries = [];


        var theIndex = -1;
        for (var i = 0; i < existingEntries.length; i++) { // search if product ID already in localstraoge
            if (existingEntries[i].id == new_search) {
        var idToRemove= existingEntries[i].id;
        //console.log(idToRemove);
                theIndex = i;
                break;
            }
        }
        //alert(theIndex);

        if (theIndex == -1){ // not present => add
            var entryId = new_search;
            var entryTitle = title;
            var entrySlug = slug;
            var entryImage = image;
            var entryBest_price = best_price;
            var entryTotal_in_stock = total_in_stock;

            var date = new Date();
             date.setTime(date.getTime());
             var date_product = date.toGMTString();

            var entry = {
                "id": entryId,
                "title": entryTitle,
                "slug": entrySlug,
                "image": entryImage,
                "best_price": entryBest_price,
                "total_in_stock": entryTotal_in_stock,
                "date": date_product
            };
            // Save allEntries back to local storage
            existingEntries.push(entry);
            //sorted by date
            var sortedExistingEntries = existingEntries.sort(function compare(a, b) {
              var dateA = new Date(a.date);
              var dateB = new Date(b.date);
              return dateB - dateA;
            });
            // max 12 products
            if(Object.keys(sortedExistingEntries).length === 13) sortedExistingEntries.pop();

            localStorage.setItem(name, JSON.stringify(sortedExistingEntries));

        } else {
            var removeIndex = existingEntries.map(function(item) { return item.id; }).indexOf(idToRemove);
      existingEntries.splice(removeIndex,1);
      localStorage.setItem(name, JSON.stringify(existingEntries));

    }
    }
}