简体   繁体   中英

How can I add Items to my sessionStorage in a little amount of code?

I want my users to click on different <a> s. After clicking on two of them I want to lead my user to another site. A different combination of clicked <a> s should lead to a different site.

I basically know, how to do it, but my code would be very, very long and it would take a lot of time to fill in every command for each combination.

As I am relatively new to javascript, I have no idea how to shorten my code.

Until now, this is my code:

var stufe = sessionStorage.getItem('stufe');
var fach = sessionStorage.getItem("fach");

if(stufe == "c5"){
          if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "mathe"){

          }
          else if(fach == "englisch"){

          }
          else if(fach == "religion"){

          }
          else if(fach == "musik"){

          }
          else if(fach == "kunst"){

          }
          else if(fach == "geografie"){

          }
          else if(fach == "sport"){

          }
          else if(fach == "bio"){

          }
          else if(fach == "chemie"){

          }
          else if(fach == "physik"){

          }
          else if(fach == "französisch"){

          }
          else if(fach == "latein"){

          }
          else if(fach == "nwt"){

          }
          else if(fach == "imp"){

          }
          else if(fach == "italienisch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
          else if(fach == "deutsch"){

          }
        }

It will be repeated again at least five times. And I would have to fill in window.location.replace(...) under each else if() . So the code would be huge.

It's all in German, so if you need any translation, please tell me. As well if there is any information missing, please tell me.

I hope you can help me. Daniel.

You could have an object with the following structure for each of your subjects, the object keys would be the route name and the value the route to navigate to:

const subjects = {
  chemie: 'url-to-chemie...',
  bio: 'url-to-bio...',
  kust: 'url-to-kust...',
  sport: 'url-to-sport...',
}

And instead of all your if's you could, assuming navigate is a function that navigates to a given url:

navigate(subjects[fach]);

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