简体   繁体   中英

jQuery - Updating and saving changes using local storage

I have a function that Creates new items and allows you to Delete, Update and Save the inputs on these items using localStorage

However, if I have more than one item and then update and save the changes, those changes are applied over all items.

The problem is encountered at the $(".save").click(function() but I'm not sure I have set up my .items with a proper array.

Since I use localStorage the working code can be found in the pen below:

https://codepen.io/moofawsaw/pen/NoBQKV

window.localStorage.clear();
//create localStorage item
if (!localStorage.getItem("_storage")) {
  localStorage.setItem("_storage", "");
}
//set data to localStorage function
function saveData() {
  localStorage.setItem("_storage", $("#content").html());
}
// Open the create dialgoue:
$(".add").on("click", function() {
  $(".create").toggle();
});
//Save the entered inputs and post the item:
$(".post").click(function() {
  var id = $(".createtext").val();
  var createtitle = $(".createtitle").val();
  var item = "";
  if (id[0]) {
    for (var i = 0; i < id.length; i++) {
      item += "<div>" + id[i] + "</div>";
    }
  } else {
    item = "<div>Click update to add a card</div>";
  }
  $("#content").append(
    '<div class="item">' +
      '<div class="title">' +
      createtitle +
      "</div>" +
      "<div class='text'>" +
      id +
      "</div>" +
      '<button class="delete">Delete</button>' +
      '<button class="update">Update</button>' +
      "</div>"
  );
  $(".createtitle").val("");
  $(".createtext").val("");
  $(".create").toggle();
  saveData();
});
//Close out of creating a new item
$(".close").click(function() {
  $(".createtitle").val("");
  $(".createtext").val("");
  $(".create").toggle();
});
//Get inputs and open edit window to update the items:
$("#content").on("click", ".update", function() {
  var item = $(this).closest(".item");
  $(".updatetext").val(
    $(this)
      .closest(".item")
      .find(".text")
      .text()
  );
  $(".updatetitle").val(
    $(this)
      .closest(".item")
      .find(".title")
      .text()
  );
  $(".edit").toggle();
});
//Save changes and update the items (error:changes all items when clicked):
$(".save").click(function() {
  var id = $(".updatetext").val();
  var title = $(".updatetitle").val();
  var item = "";
  if (id[0]) {
    for (var i = 0; i < id.length; i++) {
      item += "<div>" + id[i] + "</div>";
    }
  } else {
    item = "<p>Click edit to add a card</p>";
  }
  $(".item").each(function() {
    $(this).html(
      '<div class="title">' +
        title +
        "</div>" +
        "<div class='text'>" +
        id +
        "</div>" +
        '<button class="delete">Deleted(2)</button>' +
        '<button class="update">Updated(2)</button>'
    );
  });
  $(".updatetext").val("");
  $(".updatetitle").val("");
  $(".edit").toggle();
  saveData();
});
//Discard any of these changes:
$(".discard").click(function() {
  $(".updatetext").val("");
  $(".updatetitle").val("");
  $(".edit").toggle();
});
//Delete an item:
$("#content").on("click", ".delete", function() {
  $(this)
    .closest(".item")
    .remove();
  saveData();
});
$(function() {
  if (localStorage.getItem("_storage")) {
    $("#content").html(localStorage.getItem("_storage"));
  }
});

Point is, you call .each() in your update callback.

$(".item").each(function() {
    $(this).html(
      '<div class="title"> ....'
    );
  });

This literally means "Find all DOM elements with item class and replace their contents with given html.

But you need to replace contents of the one specific element, on which Update button was clicked. To do so, you need to persist that element somehow.

One of the ways to do that with minimum changes to your code - introduce a variable in a scope available for both update and save functions. But in your case it would be a global variable, and those are not generally a good idea.

So I'd suggest to wrap all your code into a function (like $(function() {}); . Then you can introduce a local variable:

$(function () {
  // define it
  var $selectedItem;

  // assign a value in the update click callback
  $('#content').on('click', '.update', function () {
    $selectedItem = $(this).closest('.item');
    // ...
  });

  // read the value in the save click callback
  $('.save').click(function () {
    // ...
    $selectedItem.html('...');
    // ...
  });
});

Example: https://codepen.io/anon/pen/GzXaoV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM