我的 HTML 代码如下所示(如下所示)。
<div class='row hide' data-step='{$row['qid']}' data-title='{$row['question']}'>";
while($row1=mysql_fetch_array($result1,MYSQL_ASSOC)){
echo "<div class='col-lg-3 col-md-4 col-s-6 thumb' >
<a class='thumbnail btt' href='#' id='{$row1['imageid']}'>
<img class='' src='{$row1['thumbpath']}' alt=''>
<div class='overlay'> </div>
</a>
</div>";
}
echo "</div>";
图像将通过循环逐一显示,我添加了叠加层,因此单击它时它将成为荧光笔。我使用户可以选择多个图像。这样您就可以突出显示多个图像。
单击图像时,我将其 ID 存储在本地存储中。现在我的 jquery 是:
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
$(function () {
$('.btt').click(function () {
var id = $(this).attr('id');
storeId(id);
$('#currentLCV').text(localStorage.getItem('reportArray'));
});
});
$('.btt').click(function(){
$(this).toggleClass('overlay overlay2');
});
我可以通过类为#currentLCV 的 div 再次在 HTML 中显示本地存储值,所以现在这个工作是个问题。
但是,我想要一个切换选项,如果用户单击该图像,它会将 id 保存在本地存储中,如果用户再次单击同一图像,则该 id 将从本地存储中删除。
有人可以帮忙吗?
最佳答案
你可以这样使用:
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}
}
function unStoreId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
var indx = ids.indexOf(id);
if (indx !== -1) {
ids.splice(indx,1);
localStorage.setItem('reportArray', JSON.stringify(ids));
}
}
$('.btt').click(function () {
var id = $(this).attr('id');
$(this).toggleClass('overlay overlay2 stored');
if($(this).hasClass("stored")) {
unStoreId(id);
} else {
storeId(id);
}
$('#currentLCV').text(localStorage.getItem('reportArray'));
});
注意将 .btt
事件合并在一起并删除了函数包装器。
关于javascript - jquery toggle img 单击并在单击时从本地存储中存储或删除 img id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40299153/