คุณสมบัติ sessionStorage หน้าต่าง HTML ช่วยให้เราสามารถจัดเก็บข้อมูลคู่คีย์/ค่าในเว็บเบราว์เซอร์ได้เพียงเซสชันเดียวเท่านั้น ซึ่งหมายความว่าข้อมูลจะถูกลบออกเมื่อปิดแท็บเบราว์เซอร์
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์ -
window.sessionStorage
ให้เราดูตัวอย่างของ HTML Window sessionStorage คุณสมบัติ -
ตัวอย่าง
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background-color: #8BC6EC;
background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat;
text-align: center;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 30%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
.show{
font-size:1.2rem;
}
</style>
<body>
<h1>HTML Window sessionStorage Property Demo</h1>
<button onclick="store()" class="btn">Store 'John Smith' Name to sessionStorage</button>
<button onclick="display()" class="btn">Display sessionStorage stored value</button>
<div class="show"></div>
<script>
function store(){
sessionStorage.setItem('firstName','John');
sessionStorage.setItem('lastName','Smith');
document.querySelector('.show').innerHTML='Name store successfully';
}
function display(){
var firstName=sessionStorage.getItem('firstName');
var lastName=sessionStorage.getItem('lastName');
document.querySelector('.show').innerHTML='Name stored in sessionStorage is: '+ firstName +' '+lastName;
}
</script>
</body>
</html> ผลลัพธ์

คลิกที่ “จัดเก็บ 'John Smith ’ ปุ่ม Name to sessionStorage” สำหรับจัดเก็บชื่อใน sessionStorage:

ตอนนี้คลิกที่ “แสดงค่า sessionStorage ที่เก็บไว้ ” เพื่อแสดงค่าที่เก็บไว้ -

ตอนนี้ คุณยังสามารถเปิดที่เก็บข้อมูลเซสชั่นในเครื่องมือ dev ของคุณเพื่อทำความเข้าใจวิธีการทำงาน -
