HTML and CSS Reference
In-Depth Information
sessionStorage.setItem(“keyName”, value );
h e
key
must be a string, while the
value
can be any acceptable data type — number, text,
Boolean, object, function. h e following represent some valid data assignments:
this.myKey=“secondKey”; //Key name assigned to property
function eek() //A function with a return value
{
return “eeeek!”;
}
jill=“My name is Jill”; //A variable
//Assign values to keys
sessionStorage.setItem(“firstKey”,88); //A number (numeric literal)
sessionStorage.setItem(this.myKey,true ); //Boolean
sessionStorage.setItem(“thirdKey”,eek() ); //Function
sessionStorage.setItem(“fourthKey”,”My name is Jack” ); //String literal
sessionStorage.setItem(“fifthKey”,jill ); //Variable
As you can see, you can use variables for both keys and their values. As long as the variable
(or property) is a string, it can be used as a
key
— you could even use a function that returns
a string as a key. A value can be a string or nonstring.
Once you have stored data, you need a way to retrieve it with a getter method. h e following
shows the general format for getting the stored data — you have to know the
key
name for
every value you want to retrieve.
313
sessionStorage.getItem(“keyName”);
You can think of the
key
name in the same way as you do a variable name. If you know the
variable name, you can i nd its value. Key names work the same way.
h is next program (
SessionStore.html
in this chapter's folder at
www.wiley.com/
go/smashinghtml5
) provides a simple illustration of how to work with session storage.
You'll probably be reminded of working with variables because the values are extant only as
long as you don't change the page.
<
!
DOCTYPE HTML
>
<
html
>
<
head
>
<
script
type
=
“text/javascript”
>
StorageMaster=new Object();
//Set values
StorageMaster.setPositions=function()
{
sessionStorage.setItem(“firstBase”,document.players.firstBase.value );
sessionStorage.setItem(“secondBase”,document.players.secondBase.value );
sessionStorage.setItem(“thirdBase”,document.players.thirdBase.value );
}
//Get values