简体   繁体   English

如何在javascript中保存更改状态

[英]How to save change state in javascript

While returning back from the link in the second tab ie from swiggy, it always redirecting to first tab从第二个选项卡中的链接返回时,即从 swiggy,它总是重定向到第一个选项卡

How can I save the state change?如何保存状态更改?

<div class="tab">
  <button class="tablinks" onclick="openFood(event, 'Zomato')" id="defaultOpen">Zomato</button>
  <button class="tablinks" onclick="openFood(event, 'Swiggy')">Swiggy</button>
</div>

<div id="Zomato" class="tabcontent">
  <h3>Zomato</h3>
  <a href="https://www.zomato.com/kingman-ks">Zomato</a>
</div>

<div id="Swiggy" class="tabcontent">
  <h3>Swiggy</h3>
   <a href="https://www.swiggy.com/">Swiggy</a>
</div>
<script>
function openFood(evt, FoodVendor) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(FoodVendor).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
   

Put simply, your JavaScript runs each time the page is refreshed;简而言之,每次刷新页面时,您的 JavaScript 都会运行; when a user clicks one of the links in the DOM (or what you've written between html tags), the script is run from top to bottom with no idea of what happened previously.当用户单击 DOM 中的链接之一(或您在 html 标签之间编写的内容)时,脚本从上到下运行,不知道之前发生了什么。

State management is a difficult but common problem in modern user interfaces, which is why we have JavaScript libraries like Angular , React , Vue , JQuery UI , and others to take care of the complex under-the-hood concerns and allow your UI's state to persist and your components to be reactive (ie a user clicks a tab and the active class is applied without a refresh).状态管理在现代用户界面中是一个困难但常见的问题,这就是为什么我们拥有AngularReactVueJQuery UI等 JavaScript 库来处理复杂的底层问题并允许您的 UI 状态持久化并且您的组件是反应式的(即用户单击选项卡,并且无需刷新即可应用活动类)。

If you need a super simple implementation that persists across refreshes you could:如果您需要一个在刷新中持续存在的超级简单实现,您可以:

  1. Use Local Storage or Session Storage to maintain the active tab, eg使用本地存储或会话存储来维护活动选项卡,例如
window.localStorage.setItem('activeTab', 'Swiggy');
// after user refreshes
const id = window.localStorage.getItem('activeTab');
const el = document.getElementById(id);
el.className += "active";
// (you'll also have to remove the active class from the "default" active tab etc.)
  1. Use a query string , eg使用查询字符串,例如
// user navigates to https://yoursite.com/yourendpoint?activeTab=Swiggy
function checkForActiveTabQueryString() {
  const params = new URLSearchParams(window.location.search);
  const activeTab = params.get("activeTab");

  if (activeTab) {
    const el = document.getElementById(activeTab);
    if (el) {
      el.className += "active";
    }
    // you'll have to remove the active class from the "default" tab, 
    // etc.
  }
}

You can use HTML5 LocalStorage Object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload.您可以使用 HTML5 LocalStorage Object在浏览器中本地保存当前选项卡的一些参数,并将其取回以在页面重新加载时选择最后一个活动选项卡。 Check this tutorial.检查教程。

What I've changed (add/remove) :改变了什么(添加/删除)

  1. Remove DefaultOpen删除默认打开

    But instead I added ' active ' class to Zomato Button.但相反,我向Zomato按钮添加了“活动”类。 And set display:none to tabcontent .并将display:none设置为tabcontent

  2. Add Local Storage添加本地存储

    • Everytime the tab changes ie everytime openFood() is called, we save the currentState to localStorage with variable name activeTab (value is either 'Zomato' or 'Swiggy').每次选项卡更改时,每次openFood() ,我们将 currentState 保存到 localStorage,变量名称为activeTab (值为“Zomato”或“Swiggy”)。

      localStorage.setItem('activeTab', FoodVendor);

    • When the page loads, we check activeTab value and decide which tab to open.当页面加载时,我们检查activeTab值并决定打开哪个选项卡。

       $(document).ready(function(){ var activeTab = localStorage.getItem('activeTab'); if (activeTab == 'Swiggy'){ openFood('SwiggyTab', 'Swiggy'); } else if(activeTab == 'Zomato'){ openFood('ZomatoTab', 'Zomato'); } });

CSS CSS

<style type="text/css">
    div.tabcontent{
        display: none;
    }
</style>

HTML HTML

<div class="tab">
  <button class="tablinks active" id="ZomatoTab" onclick="openFood('ZomatoTab', 'Zomato')">Zomato</button>
  <button class="tablinks" id="SwiggyTab" onclick="openFood('SwiggyTab', 'Swiggy')">Swiggy</button>
</div>

<div id="Zomato" class="tabcontent">
  <h3>Zomato</h3>
  <a href="https://www.zomato.com/kingman-ks">Zomato</a>
</div>

<div id="Swiggy" class="tabcontent">
  <h3>Swiggy</h3>
   <a href="https://www.swiggy.com/">Swiggy</a>
</div>

JavaScript JavaScript

<script type="text/javascript">
    $(document).ready(function(){
        //get activeTab from LocalStorage
        var activeTab = localStorage.getItem('activeTab');
        //Decide which tab to open
        if (activeTab == 'Swiggy'){
            openFood('SwiggyTab', 'Swiggy');
        }
        else{
            openFood('ZomatoTab', 'Zomato');
        }
    });
    function openFood(id, FoodVendor) {
      var i, tabcontent, tablinks;
      tabcontent = document.getElementsByClassName("tabcontent");
      for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
      }
      tablinks = document.getElementsByClassName("tablinks");
      for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
      }
      
      document.getElementById(FoodVendor).style.display = "block";
      document.getElementById(id).className += " active";
      
      //Save the latest activeTab
      localStorage.setItem('activeTab', FoodVendor);
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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