我想在我的一个元素中添加“添加到收藏夹/书签”功能,但对此一无所知。
基本上,如果用户想从收藏夹中添加/删除,我正在使用 Bootstrap 字形图标来选择它。我做了一些研究,发现 html5 localStorage 概念很合适,但无法真正弄清楚它对我的元素的确切作用。如果这里有人可以指导我,那将是一个很大的帮助。
这是 html:
<h1>test</h1>
<table class="'basic">
<tr>
<td><div class="glyphicon glyphicon-star-empty icon bkmark_icon"> </div></td>
<td>A</td>
</tr>
<tr>
<td><div class="glyphicon glyphicon-star-empty icon bkmark_icon"> </div></td>
<td>B</td>
</tr>
<tr>
<td><div class="glyphicon glyphicon-star-empty icon bkmark_icon"> </div></td>
<td>C</td>
</tr>
</table>
<br><button class="btn">You have selected:</button>
因为我不太了解localStorage在jQuery中的实现,所以没有添加它,但这是js文件现在的内容:
$(function() {
$(document).on('click', '.bkmark_icon', function(){
$(this).toggleClass('glyphicon-star-empty glyphicon-star');
// localStorage.setItem('display', $(this).is(':visible'));
});
$(document).on('click', '.btn', function(){
var bkmark_item = '<table><tr><td><div class="glyphicon glyphicon-star icon bkmark_icon"></div></td><td>*selected*</td></tr></table>';
$(bkmark_item).insertAfter('h1');
});
});
我确实搜索了一下,发现这个堆栈溢出 answer合适的。
我需要什么?
- 当用户点击 glyphicon-star-empty 时,它应该切换到 glyphicon-star 并且相关元素应该添加到 localStorage(即收藏夹)。
- 当用户点击“您已选择:”按钮时,它应该删除表格中的当前内容并仅显示收藏的元素(在同一页面上)并提供取消收藏的选项。
这里是 fiddle我正在研究。
最佳答案
尝试创建一个 JavaScript 对象并将其序列化以将其保存在 localStorage 中。使用这样的东西 -
var bookmarkedItems = [];
function ItemObject(name, content)
{
this.name = name;
this.content = content;
}
function addItem()
{
bookmarkedItems.push(new ItemObject('Item1', 'Content1'));
}
function saveToLocalStorage(item)
{
var ob = localStorage.get('KEY');
if(ob)
{
bookmarkedItems = JSON.parse(ob);
}
bookmarkedItems.push(item);
localStorage.set('KEY', JSON.stringify(bookmarkedItems);
}
或
引用下面的代码-
var storageService = function () {
var STORAGE_KEY = "bookmarkitems";
var bookmarkitems = {};
var init = function () {
bookmarkitems = sessionStorage.getItem(STORAGE_KEY);
if (bookmarkitems) {
bookmarkitems = JSON.parse(bookmarkitems);
}
else {
bookmarkitems = {};
}
};
var set = function (key, value) {
bookmarkitems[key] = value;
updateStorage();
};
var get = function (key) {
return bookmarkitems[key];
};
var updateStorage = function () {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(bookmarkitems));
};
return {
init: init,
set: set,
get: get,
updateStorage: updateStorage
};
};
关于javascript - 使用 HTML5 localStorage 和 jQuery 添加到收藏夹/书签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37253177/