我有这段代码,根据列表项的id号,在click to localStorage上保存一个列表项。在另一个页面上,我可以加载保存的任何列表项。
var save1075 = $('#store-1075').get(0);
$('#store-1075').on('click', function () {
var storeStorageKey1075 = $(this).attr('id');
localStorage.setItem('storeStorageKey1075', $(this).attr('id'));
localStorage.setItem('storeStorageKey1075', this.innerHTML);
});
if ( localStorage.getItem('storeStorageKey1075') ) {
save1075.innerHTML = localStorage.getItem('storeStorageKey1075');
}
var storeStorageKey1075 = $(this).attr('id');
if ( localStorage.getItem('storeStorageKey1075') ) {
storeStorageKey1075 = localStorage.getItem('storeStorageKey1075');
}
现在我必须为每个单独的id号重复那段代码,而我试图将id号变成一个变量,在点击时循环遍历所有可能的id号,但只保存特定id的id。也许就是这样的事情:
var id = //some sort of loop or array of possible ids.
var save = $('#store-'+id).get(0);
$('#store-'+id).on('click', function () {
var storeStorageKey = $(this).attr('id');
localStorage.setItem('storeStorageKey', $(this).attr('id'));
localStorage.setItem('storeStorageKey', this.innerHTML);
});
if ( localStorage.getItem('storeStorageKey') ) {
save.innerHTML = localStorage.getItem('storeStorageKey');
}
var storeStorageKey = $(this).attr('id');
if ( localStorage.getItem('storeStorageKey') ) {
storeStorageKey = localStorage.getItem('storeStorageKey');
}
每个列表项都具有相同的“store-”前缀,并且这些数字没有特定的顺序,但每次创建新的商店位置时都会随机生成。
答案 0 :(得分:7)
显而易见的事情是添加一个类,但你也可以:
var elems = $( "[id^='store']")
elems.on( "click", function() {//Save html on click
localStorage.setItem( this.id, this.innerHTML );
});
//Retrieve html
elems.each( function() {
var html = localStorage.getItem( this.id );
if( html ) {
$(this).html( html );
}
});
答案 1 :(得分:2)
这会遍历以storeStorageKey
开头的所有键:
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
if (/^storeStorageKey/.test(key)) {
var item = localStorage.getItem(key);
// do something with item
}
}
答案 2 :(得分:0)
我建议添加一个类来表示某个项目是可存储的,而不是在ID中使用前缀:
<div class="storable" id="store-1234">...</div>
然后你可以使用该课程一次性选择所有可存储的东西:
$('.storable').on('click', function () {
var storeStorageKey = $(this).attr('id');
...
});