About an array that is repeatedly added and deleted

Asked 2 years ago, Updated 2 years ago, 49 views

On the station list page like the one below, when you click on the box class in jQuery's toggleClass, the box is colored by repeated addition and deletion of the onbox class.I understand that if you array the states of the lines "Only the boxes on the lines of Tokyo and Odawara are clicked and colored" and save them in LocalStorage, it will not be reset even if you reload or load documents from now on.

However, we are at a standstill in creating an important array.
An empty array is created, and the box elements of the lines Tokyo and Shinagawa are clicked on there, and the information is stored in the array when onbox adds it.Delete the information on the line when the box element is clicked again and the onbox is deleted.I have the image that it doesn't work.
It's like saving or deleting id elements with onbox in the array.The hasClass returned true and false in an array, and so on.

<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <metacharset="utf-8">
    <style>
    .box{
      margin —05px00;
      padding —10px1px10px30px;
      width —20px;
      height —50px;
      border —0.5px solid#000;
      display:inline;
    }

    .onbox{
      margin —05px00;
      padding —10px1px10px30px;
      width —20px;
      height —50px;
      border —0.5px solid#cc;
      display:inline;
      background: #000;
    }
    </style>

    <title> East Sea Expressway </title>
  </head>
  <body>
    <div class="wreppar">
    <div class="head">
    <h1> East Sea Expressway </h1>
  </div>

  <h2> Station List</h2>
    <ul>
      <li><divid="st1" class="box"></div>Tokyo</li>
      <li><divid="st2" class="box"></div>Shinagawa</li>
      <li><div class="box"></div>Shin-Yokohama</li>
      <li><div class="box"></div> Odawara</li>
      <li><div class="box"></div>Atami</li>
    </ul>

  </div>
  </body>
</html>
$(function(){
    $('.box').on('click', function(){
        $(this).toggleClass('onbox');
    });
});

Code for creating an array:

$('.box').on('click', function(){
  let slc = [ ];

  letp = $('#st1') .hasClass('onbox');
  if(p){
    slc.shift(p);
    slc.push(p);
  } else{
    slc.shift(p);
    slc.push(p);
  }

  letter=$('#st2').hasClass('onbox');
  if(r){
    slc.shift(r);
    slc.push(r);
  } else{
    slc.shift(r);
    slc.push(r);
  }
});

javascript jquery

2022-09-29 22:24

2 Answers

One way to do this is to assign a unique id to each element using the custom data attribute or the id attribute and store the id of the clicked element as an array in localStorage.

Note that the Storage object's key and value support only strings, so you need to convert the array to string format [1].

[1]

11.2.1 The Storage interface[1]

[1]

Each Storage object offers access to a list of key/value pairs, which are some items called items. Keys are strings.Any string (including the empty string) is a valid key.Values are similar strings.

The solution is to convert an array to a JSON string using the JSON.stringify method.

 constarr=[1,2,3];
const stringify = JSON.stringify(arr);

console.log(stringify); // = > [1, 2, 3]
console.log (JSON.parse(stringify)) ;//=>Array(3) [1,2,3]

With the above in mind, looking at the code in the questionnaire, you can see that the id attribute is only assigned halfway through the list item.Therefore, first assign the id attribute to all list items.

<ul>
  <li><divid="st1" class="box"></div>Tokyo</li>
  <li><divid="st2" class="box"></div>Shinagawa</li>
  <li><divid="st3" class="box"></div>Shin-Yokohama</li>
  <li><divid="st4" class="box"></div> Odawara</li>
  <li><divid="st5" class="box"></div>Atami</li>
</ul>

Next, if you look at jQuery, the variable slc is substituted with an empty array.This time, if there is an array in localStorage, you need to retrieve the array from localStorage, so you can write the initialization part of this variable slc as follows:

Note that you must now use the JSON.parse method to convert the string to an array in order to save the array as a JSON string

$(function(){
  $(".box").on("click", function(){
    $(this).toggleClass("onbox");
    let slc = JSON.parse(localStorage.getItem("clicked_boxes")||[];
    // The following code is omitted.
  });
});

And if you look at the following code, you can see that shift, push method arguments.Passed the results of the https://api.jquery.com/hasClass/"rel="nofollow noreferrer">hasClass method.Here, I would probably like to do something like "If the onbox class is applied to the specified id element, remove the id from the array, or add the id to the array."

However, the shift method does not use arguments, and the hasClass method returns a true value.Therefore, adding and removing id will not work properly and cannot determine which element was clicked.

Therefore, you can delete the id in the array using the findIndex and splice methods and hasClass method should only be used to determine if the element has an onbox class.Here, removing elements using the findIndex methods and splice methods works as follows:

vararr=[1,2,3,4,5];
varindex=arr.findIndex(v=>v===3);

console.log(arr);//=>Array(5) [1,2,3,4,5]
console.log(index);//=>2

arr.splice(index,1);

console.log(arr);//=>Array(4) [1,2,4,5]

Also, since only clicked elements are involved in this process, only clicked elements are involved in this process using the this keyword.

[2]

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use$(this).

Finally, use the setItem method to save the value to localStorage.Note that you must now use the JSON.stringify method to convert an array to a JSON string

.

If you do the above to assign an onbox class to the id element stored in localStorage when loading the page, the final code will be as follows:

$(function(){
  varslc=JSON.parse(localStorage.getItem("clicked_boxes")))||[];

  $.map(slc, function(box){
    $("#"+box).addClass("onbox");
  });

  $(".box").on("click", function(){
    varslc=JSON.parse(localStorage.getItem("clicked_boxes")))||[];

    if($(this).hasClass("onbox")){
      varindex=slc.findIndex(v=>v===$(this).attr("id"));
      slc.splice(index,1);
    } else{
      slc.push($(this).attr("id"));
    }

    localStorage.setItem("clicked_boxes", JSON.stringify(slc));
    $(this).toggleClass("onbox");
  });
});
.box{
  margin —05px00;
  padding —10px1px10px30px;
  width —20px;
  height —50px;
  border —0.5px solid#000;
  display:inline;
}

.onbox{
  margin —05px00;
  padding —10px1px10px30px;
  width —20px;
  height —50px;
  border —0.5px solid#cc;
  display:inline;
  background: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wreppar">
  <div class="head">
    <h1> East Sea Expressway </h1>
  </div>

  <h2> Station List</h2>
  <ul>
    <li><divid="st1" class="box"></div>Tokyo</li>
    <li><divid="st2" class="box"></div>Shinagawa</li>
    <li><divid="st3" class="box"></div>Shin-Yokohama</li>
    <li><divid="st4" class="box"></div> Odawara</li>
    <li><divid="st5" class="box"></div>Atami</li>
  </ul>
</div>

This time, we added and deleted the id to localStorage after making a decision every time for the elements clicked, but I think the questioner can do what he wants to do by saving only the elements with the onbox class in localStorage as shown below.

$(function(){
  var clicked_boxes=JSON.parse(localStorage.getItem("clicked_boxes")||[];
  $.map(clicked_boxes, function(box){
    $("[data-station-id='"+box+"]" ).addClass("onbox";
  });

  $(".box").on("click", function(){
    $(this).toggleClass("onbox");

    varclicked_boxes=$.map($(".box.onbox"), function(box){
      return$(box).data("station-id");
    });

    localStorage.setItem("clicked_boxes", JSON.stringify(clicked_boxes)));
  });
});
.box{
  margin —05px00;
  padding —10px1px10px30px;
  width —20px;
  height —50px;
  border —0.5px solid#000;
  display:inline;
}

.onbox{
  margin —05px00;
  padding —10px1px10px30px;
  width —20px;
  height —50px;
  border —0.5px solid#cc;
  display:inline;
  background: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wreppar">
  <div class="head">
    <h1> East Sea Expressway </h1>
  </div>
  <h2> Station List</h2>
  <ul>
    <li>
      <div class="box" data-station-id="1"></div>Tokyo</li>
    <li>
      <div class="box" data-station-id="2"></div>Shinagawa</li>
    <li>
      <div class="box" data-station-id="3"></div>Shin-Yokohama</li>
    <li>
      <div class="box" data-station-id="4"></div> Odawara</li>
    <li>
      <div class="box" data-station-id="5"></div>Atami</li>
  </ul>
</div>


2022-09-29 22:24

The basic way of thinking is the same as before, but I changed my mind a little.

  • Use <input type="checkbox">> for toggle processing that affects the design
  • localStorage uses "JSONized Array Initiator"
  • Use newSet for the add/delete process
  • Delete localStrage items if the checked station is "0"

'use strict';
function handleChange(event) {
  const input = event.currentTarget, station = input.value;
  conststationList=event.data;

  input.checked?stationList.add(station):stationList.delete(station);
  stationList.size?localStorage.setItem('station-list', JSON.stringify(Array.from(stationList))):localStorage.removeItem('station-list');
}

function main() {
  conststationList=JSON.parse(localStorage.getItem('station-list')))||[];

  jQuery(stationList.map(station)=>'input[type="checkbox"][name="station"][value="'+station+']').join()) .prop('checked', true);

  jQuery('#station-list').on('change','input[type="checkbox"][name="station"]', newSet(stationList), handleChange);
}

main();
 input [ type = "checkbox" ] [ name = "station" ] {
  display: none;
}

input [ type = "checkbox" ] [ name = "station" ] + span: before {
  display:inline-block;
  margin —03px00;
  width —10px;
  height —10px;
  border —solid1px black;
  background-color:white;
  US>content:
}

input [ type = "checkbox" ] [ name = "station" ]: checked + span: before {
  background-color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2id="h-station-list"> Station List</h2>
<ulid="station-list">
  <li>label><input type="checkbox" name="station" value="Tokyo"/>span>Tokyo</span><label><</li>
  <li>label><input type="checkbox" name="station" value="New Yokohama"/>span>New Yokohama></label><li>
  <li>label><input type="checkbox" name="station" value="Odawara"/>span>Odawara></label><<li>
  <li>label><input type="checkbox" name="station" value="Atami"/>span>Atami><Atami></label><<li>
</ul>


2022-09-29 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.