How to make my website remember which CTA has been pressed to redirect

主宰稳场 提交于 2020-06-17 09:33:00

问题


I'm trying to make an page which is in both Spanish and English, so what I want to do is create a main page where the user must choose the language and once he does, I want the page to remember which language was chosen so instead of opening the main page again, it opens the language previously chosen.

What would be the best approach?

EDIT-- I tried the suggestion of localStorage, I am stuck, never used JavaScript so I should have seen this coming. I can write in 'locale' 'es' or 'en' but I can't redirect at all. This is the code:

<script>
    (function (){
  'use strict';

  var eng = document.querySelector('.eng')

  function setLocalStorage(){
     eng.addEventListener('click', () => {
      localStorage.setItem('locale','en')
    })
  }
  setLocalStorage()

}());
        (function (){
  'use strict';

  var esp = document.querySelector('.esp')

  function setLocalStorage(){
     esp.addEventListener('click', () => {
      localStorage.setItem('locale','es')
    })
  }
  setLocalStorage()

}());
        if (localStorage.getItem('en') === 'en') { window.location='eng.html'; }
        if (localStorage.getItem('es') === 'es') { window.location='esp.html'; }
    </script>

回答1:


You can use the localStorage. see: mdn localStorage

localStorage.setItem('locale', 'en'); // or es

After reloading the page you can get the value back:

localStorage.getItem('locale'); // --> en

(Attention: At first start your getItem will return undefined.)

You can change your code into this:

(function () {
  'use strict';

  const locale = localStorage.getItem('locale');

  if (locale === 'en') {
    window.location = 'eng.html';

  } else if (locale === 'es') {
    window.location = 'esp.html';

  } else {
    // first visit:

    document
      .querySelector('.eng')
      .addEventListener('click', () => {
        localStorage.setItem('locale', 'en')
      });

    document
      .querySelector('.esp')
      .addEventListener('click', () => {
        localStorage.setItem('locale', 'es')
      });    
  }

}());


来源:https://stackoverflow.com/questions/61982816/how-to-make-my-website-remember-which-cta-has-been-pressed-to-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!