Html 单击按钮将输入数据保存到 localStorage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10333230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:00:10  来源:igfitidea点击:

Save input data to localStorage on button click

htmlbuttoninputlocal-storage

提问by user1358625

I am trying to build my first web application. In my app I need to have a settings panel, but I have no idea how to do it. I've been searching the web and came across a HTML5 localStorage, which I believe might be the best way to do the things. But the problem is I have no idea how to use it.

我正在尝试构建我的第一个 Web 应用程序。在我的应用程序中,我需要一个设置面板,但我不知道该怎么做。我一直在网上搜索并遇到了一个 HTML5 localStorage,我相信这可能是做这些事情的最佳方式。但问题是我不知道如何使用它。

<input type='text' name="server" id="saveServer"/>  

How can I save data from input to localStorage when user clicks the button? Something like this?

当用户单击按钮时,如何将输入中的数据保存到 localStorage?像这样的东西?

<input type='text' name="server" id="saveServer"/>  

<button onclick="save_data()" type="button">Save/button>

    <script>
            function saveData(){
        localStorage.saveServer
        }
        </script>

回答by James Allardice

The localStorageobject has a setItemmethod which is used to store an item. It takes 2 arguments:

localStorage对象具有setItem用于存储项目的方法。它需要 2 个参数:

  1. A key by which you can refer to the item
  2. A value

    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.val());
    
  1. 您可以用来引用项目的键
  2. 一个值

    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.val());
    

The above code first gets a reference to the inputelement, and then stores an item ("server") in local storage with the value of the value of that inputelement.

上面的代码首先获取对input元素的引用,然后将一个项(“服务器”)与该input元素的值一起存储在本地存储中。

You can retrieve the value by calling getItem:

您可以通过调用来检索值getItem

var storedValue = localStorage.getItem("server");

回答by Stephan

This worked for me. For setting I placed .valuebehind the varand called the varin the setItem:

这对我有用。对于设置,我放在了.value后面var并在var中调用了setItem

var input = document.getElementById('saveServer').value;
localStorage.setItem('server', input);

For getting the text back:

为了取回文本:

document.getElementById('saveServer').value = localStorage.getItem('server');