简体   繁体   English

Session 存储未给出实际值

[英]Session storage not giving actual value

I'm trying to console.log a value taken from an input from session storage but it gives me " [object HTMLInputElement " but not the actual value of the input what can be done?我正在尝试 console.log 从 session 存储的输入中获取的值,但它给了我“[object HTMLInputElement”但不是输入的实际值可以做什么? Here's my code这是我的代码

let us = document.getElementById('us')
sessionStorage.setItem("user",us)
setTimeout(function() {
let h = sessionStorage.getItem("user")
console.log(h)
}, 200);

Your script is working correctly but document.getElementById('us') is html element, you store HTML element.您的脚本工作正常,但 document.getElementById('us') 是 html 元素,您存储 HTML 元素。 I think you need value or something, you write or change like this document.getElementById('us').value or what you need to do.我认为您需要价值或其他东西,您可以像这样编写或更改 document.getElementById('us').value 或您需要做的事情。

As @Huseyint said, you must use <HTMLInputElement>.value to get the value of the input field.正如@Huseyint所说,您必须使用<HTMLInputElement>.value来获取输入字段的值。 More info here .更多信息在这里 For example, your code would be rewritten like this:例如,您的代码将被重写如下:

const us = document.getElementById('us');
sessionStorage.setItem('user', us.value);
const h = sessionStorage.getItem('user');
console.log(h);

Or if you want to save all of the properties you could do something like this:或者,如果您想保存所有属性,您可以执行以下操作:

const us = document.getElementById('us');
sessionStorage.setItem('user', us);
const h = sessionStorage.getItem('user').value;
console.log(h);

Either one should work.任何一个都应该工作。 Also, note that setItem() isn't a promise so you don't need the setTimeout .另外,请注意setItem()不是 promise 所以你不需要setTimeout

Hoped this helped!希望这有帮助!

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

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