0
我有2種不同類型的按鈕,我想將用戶選擇保存到localStorage並顯示在「購物車」中。我無法弄清楚如何區分它們。現在,兩者都顯示出來。使用數據屬性設置LocalStorage
每一個按鍵都將在數據屬性設置不同的值,但有兩種類型的值 - 樓層平面圖和屬性。
JS:
function showElem1() {
var $ul = $('<ul />', { "class": "cart1" });
for (var a = 0, len = localStorage.length; a < len; a++) {
var $li = $('<li />', { text: localStorage.key(a) });
$('<span />', { "class": "removeitem", data: { remove: localStorage.key(a) }, html: " <i class='icon-trash2'></i>" })
.appendTo($li);
$li.appendTo($ul);
}
$ul.appendTo($('.cart1').empty());
};
function showElem2() {
var $ul = $('<ul />', { "class": "cart2" });
for (var a = 0, len = localStorage.length; a < len; a++) {
var $li = $('<li />', { text: localStorage.key(a) });
$('<span />', { "class": "removeitem", data: { remove: localStorage.key(a) }, html: " <i class='icon-trash2'></i>" })
.appendTo($li);
$li.appendTo($ul);
}
$ul.appendTo($('.cart2').empty());
};
showElem1();
showElem2();
$("body").on('click', '.property', function() {
if(!localStorage.getItem($(this).data('property'))) {
localStorage.setItem($(this).data('property'), 0);
}
showElem1();
});
$("body").on('click', '.floor-plan', function() {
if(!localStorage.getItem($(this).data('floorplan'))) {
localStorage.setItem($(this).data('floorplan'), 1);
}
showElem2();
});
$(".cart").on('click', '.removeitem', function() {
localStorage.removeItem($(this).data('remove'));
showElem1();
showElem2();
});
HTML:
<div class="cart">
<div class="cart1"></div>
</div>
<div class="cart">
<div class="cart2"></div>
</div>
<a data-property="Tri Estate, Kennewick, WA" class="property"> Add to Selections</a>
<a data-floorplan="Floor Plan 1" class="floor-plan">Add Floorplan</a>
我該怎麼做? – dchadney
您好@dchadney,請遵循您的代碼,也許您想要爲數據屬性添加前綴以檢測值的類型。例如:data-property =「0 | Tri Estate,Kennewick,WA」和data-floorplan =「1 | Floor Plan 1」。當從localStorage讀取時,只需檢查第一個字符是0還是1,當得到文本時記得刪除2個第一個字符。 –