使用复选框删除本地内存中存储的项目Jquery



我将项目存储在数组中,然后将数组存储在本地内存中。

我将项目打印到屏幕上,让用户看到每个项目附带的复选框。

我允许用户像这样清除本地存储中的所有项目,

$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});

我想允许用户清除他们想要的任何一个复选框项目。如何实现从数组中删除选中复选框项目的函数。

$(document).ready(function () {
localArray = [];
loadKeyWords();
function loadKeyWords() {
    $('#keyWords').html('');
    localArray = JSON.parse(localStorage.getItem('keyWords'));
    for(var i = 0; i < localArray.length; i++) {
      $('#keyWords').prepend('<li><input id="check" name="check" type="checkbox">'+localArray[i]+'</li>'); 
        }
    }
$('#add').click( function() {
   var Description = $('#description').val();
  if($("#description").val() === '') {
    $('#alert').html("<strong>Warning!</strong> You left the to-do empty");
    $('#alert').fadeIn().delay(1000).fadeOut();
    return false;
   }
   $('#form')[0].reset();
   var keyWords = $('#keyWords').html();
   localArray.push(Description);
   localStorage.setItem('keyWords', JSON.stringify(localArray));
   loadKeyWords();
   return false;
});
if(localStorage.getItem('keyWords')) {
$('#keyWords').JSON.parse(localStorage.getItem('keyWords'));
}
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});
$('#clearChecked').click( function() {
    if ($(this).is(':unchecked')) {
      localArray.push($(this).val());
    }
    else {
      if ((index = localArray.indexOf($(this).val())) !== -1) {
                    localArray.splice(index, 1);
    }
       $('#form')[0].reset();
   var keyWords = $('#keyWords').html();
   localArray.push(Description);
   localStorage.setItem('keyWords', JSON.stringify(localArray));
   loadKeyWords();
   window.location.reload();
   return false;
          }
    });
}); // End of document ready function

我的HTML

<!doctype html>
<html>
  <head>
    <title>Wuno Zensorship</title>
    <script src="jquery-1.11.3.min.js"></script>
        <script src="popup.js"></script>
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <img src="icon48.png">
 <section>
<form id="form" action="#" method="POST">
<input id="description" name="description" type="text" />
<input id="add" type="submit" value="Add" />
<button id="clearChecked">Clear Checked Items</button>
<button id="clear">Clear All</button>
</form>
<div id="alert"></div>
<ul id="keyWords"></ul>
</body>
</html>

您应该遍历ul,查找其checkbox已检查的li元素,然后将它们从localArray中删除。试试这个:

$('#clearChecked').click( function() {
    $('#keyWords > li > input:checked').each(function(){
      var desc = $(this).parent().text();
      var index = localArray.indexOf(desc);
      localArray.splice(index, 1);
    });
    ...
});

最新更新