LocalStorage local storage
settings are stored content setItem (key, value)
localStorage.setItem('leo','23');
Updating the stored content
objects [key] = value
objects .key = value
localStorage.leo = 25;
localStorage['leo'] = 24;
Obtaining storage contents getItem (key)
console.log(localStorage.getItem('leo'))
Delete stored content removeItem (key)
localStorage.removeItem('leo');
Empty the contents of memory clear ()
localStorage.clear();
Get stored content length
console.log(localStorage.length);
sessionStorage
sessionStorage.a = 10;
console.log(sessionStorage);
localStorage and sessionStorage difference
localStorage:
storage will persist
capacity 2-5MB
sessionStorage:
At the end web session expires
capacity varies, some browsers do not set limits
Storage Caution:
1, the storage capacity exceeds the limit, you need to use try catch catch the exception
2, memory type restrictions: only string
3, sessionStorage failure mechanisms:
Refresh the page can not fail sessionStorage
same URL different tabs can not be shared sessionStorage
DOT game mouse click Case:
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{margin: 0;padding: 0;list-style: none;} body{position: relative;height: 100%;} html{height: 100%;} .guai{position: absolute;left: 50%;top: 50%;margin: -75px 0 0 -100px;} .line{width: 400px;height: 20px;border:4px solid black;position: absolute;left: 50%;top: 20px;margin: 0 0 0 -204px;} .xie{width: 400px;height: 100%;background: red;transition: .3s;} </style> </head> <body> <div class='line'> <div class='xie'></div> </div> <img src="1.jpeg" class='guai'> <script type="text/javascript"> var num = 0,timer = null,max = 400, xieNode = document.querySelector('.xie'); if(localStorage.x){ max = localStorage.x; xieNode.style.width = max + 'px'; }; onclick = function(){ var r = Math.random() * 5 + 5; max -= r; localStorage.setItem('x',max); console.log(localStorage) xieNode.style.width = max + 'px'; clearInterval(timer); timer = setInterval(function(){ num++; if(num == 10){ clearInterval(timer); num = 0; document.body.style.left = 0; document.body.style.top = 0; return; }; document.body.style.left = Math.random() * -20 + 10 + 'px'; document.body.style.top = Math.random() * -20 + 10 + 'px'; },30) } </script> </body> </html>
localStorage with expired mechanisms
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> 储存数据: <input type="" name="" id='need'> 储存数据的时间: <input type="" name="" id='timer'> <Save>= 'BTN'IDButton</button> 数据展示: <span id='span'>暂无数据</span> <script type="text/javascript"> var nowTime = new Date().getMinutes(); if(nowTime >= localStorage.timer){ localStorage.clear(); } else{ if(localStorage.leo){ span.innerHTML = localStorage.leo; } } btn.onclick = function(){ localStorage.setItem('leo',need.value); localStorage.setItem('timer',new Date().getMinutes() + Number(timer.value)); span.innerHTML = localStorage.leo; }; </script> </body> </html>
HTML5 - Database: indexedDB
Create a database indexedDB.open ( 'just a name', version number)
if this data is open, is not created
version number can only go up, not down
var request = indexedDB.open('testDBLeo',6);
onsuccess database to create or open a successful
onerror failed to open (the version number can not be reduced)
function is triggered when onupgradeneeded version upgrade
// database created successfully request.onsuccess = function () { the console.log ( 'create the database successfully " ); }; // database creation fails request.onerror = function () { the console.log ( ' database read failed ' ) ; }; // database version upgrade request.onupgradeneeded = function () { the console.log ( 'version upgrade' ) };
Create a table createObjectStore
auto-incrementing - createObjectStore table inside incremented
{autoIncrement: to true}
{keyPath: data fields}
= request.onupgradeneeded function () { var DB = request.result; // a ObjectStore a table corresponding to // the specified table's primary key increment db.createObjectStore ( 'Test3', {autoIncrement: to true }); };
To set the primary key id
db.createObjectStore('test3',{keyPath: 'id'}
Uniqueness of the unique true if there are a plurality of the same situation is not written
store.createIndex('test3','name',{unique:true});
transaction using the transaction to acquire a table
readwrite read and write mode
readonly can only be read but not write
var transaction = db.transaction('test3','readwrite'); var store = transaction.objectStore('test3');
Operating Data table
Add to add the data, add readonly is being given
get into the inside of the key values can
getAll result can be obtained in the form of performance data for all of the table is an array of
put Continue to add data
delete delete a piece of data is the key parameter values
clear to delete all data
onsuccess If the command is successful callback function to execute
result you can see the relevant data
var json = [{ "id":200, "name":"Modoy", "age":"15" },{ "id":201, "name":"Busy", "age":"21" },{ "id":202, "name":"Blue", "age":"23" }] // add 添加数据 store.add(json); // 读取数据store.get()参数是主键的值 var requestNode = store.get(1); function requestNode.onsuccess =After obtaining a successful operation//() { the console.log (requestNode.result); for ( var I = 0; I <. 3; I ++ ) { the console.log ( 'name' + requestNode.result [I] .name); the console.log ( 'age, this has been '+ requestNode.result [i] .age + ' years old ' ); } };
Update data specifying the primary key
store.put({ "id":203, "name":"Sky", "age":"29" });
Get all data
var requestNode = store.getAll();
Delete the specified data id
store.delete(201);
Cursor, here represents the primary key <= 202
var requestNode = store.openCursor (IDBKeyRange.upperBound (202 )); requestNode.onsuccess = function () { // Get the value of the acquired cursor var Cursor = requestNode.result; IF (Cursor) { the console.log (cursor.value ); . Cursor Continue (); }; };
Index uniqueness
store.createIndex (table name, key value data, {UNIQUE: to true }); ---------- var index = store.index (table name) GET (key value name) .onsuccess = function () { e.target.result find the contents of data }
Range designated by the cursor:
IDBKeyRange.only // First parameter range
before upperBound // does not contain less true false comprising their own
before lowerBound // do not contain greater than or equal true false comprising their own
bound parameter is greater than 1 parameter 2 is equal to less than or equal to 3 and 4 if the parameter is false and true
true false containing not contain their own
parameters corresponds to the parameter 1 3 4 parameter corresponds to the parameter 2
Set cursor direction:
the Next order of queries
nextunique order unique query
prev reverse query
prevunique reverse unique query
var requestNode = store.openCursor(IDBKeyRange.bound(200,202),'prev');
Index and vernier combination
//指定数据表 var index = store.index('test3'); //游标指定范围 var requestNode = index.openCursor(IDBKeyRange.upperBound(31)); requestNode.onsuccess = function(){ var cursor = requestNode.result; if(cursor){ //如果查询的数据name为Leo if(cursor.value.name == 'Leo'){ // 更新数据 cursor.update({ "id":209, "name":"Leoooo", "age":31 }); } console.log(cursor.value); cursor.continue(); } };
IndexedDB与Web Storage比较:
优点:IndexedDB存储类型丰富
条件搜索强大
存储容量更大
可以在Worker中使用
缺点:兼容性问题