Đây là mã của tôi:localStorage eventHandler không nhận được gọi
<script type="text/javascript">
function getLocalStorage() {
try {
if (!! window.localStorage) return window.localStorage;
} catch(e) {
return undefined;
}
}
function getAddEventListener() {
try {
if(!! window.addEventListener) return window.addEventListener;
} catch(e) {
return undefined;
}
}
function eventHandler(e) {
alert("here we are = " + e.storageArea.traveler);
}
function testStorage() {
var db = getLocalStorage();
var addEL = getAddEventListener();
if(addEL) {
addEL('storage', eventHandler, false);
} else {
alert('This browser does not support event listeners');
}
db.setItem('traveler', 'Bill');
db.setItem('destination', 'Ventura');
db.setItem('transportation', 'Airplane');
document.getElementById('results').innerHTML = db.getItem('destination');
}
</script>
</head>
<body onload="testStorage();">
<div id="results"> </div>
</body>
</html>
Nó chèn thành công các mục trong lưu trữ địa phương và kết quả hiển thị trong 'phần tử results', nhưng eventHandler không hoạt động. Tôi làm mới cửa sổ trình duyệt và không thấy bất kỳ thông báo cảnh báo nào. Tại sao?
Điều gì xảy ra nếu bạn sử dụng 'window.addEventListener ('storage', eventHandler, false)', thay vì 'addEL ('storage', eventHandler, false)'. –