javascript - jquery toggle img 单击并在单击时从本地存储中存储或删除 img id

标签 javascript jquery css

我的 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/

相关文章:

javascript - 容器内的两个 div 重叠

javascript - 窗口滚动功能不起作用

javascript - 在 AlloyUI 3.03 中自定义和保存 Diagram Builder 的小麻烦

html - 为什么高度为:auto size to the child content and display:inline size to the grandparent?

javascript - 如何获取按键上 anchor 的 href 值?

javascript - three.js:BufferGeometry 和纹理

javascript - 在 View 中绑定(bind)数组元素

javascript - Bootstrap datepicker 在通过 javascript 函数放在页面上时不起作用

javascript - Cordova/PhoneGap Android 应用程序中的 Maxlength 和复制粘贴

html - 包装和 flex-grow : auto 的 Flexbox 问题