我們可以在瀏覽器上臨時存盤資料嗎?例如,我有頁面 A 和頁面 B
在頁面 A(a.html) 上,我想在單擊按鈕時臨時存盤文本“Helloworld”
function a(){
return "helloWorld"
}
function changePage(){
a()
window.location(b.html)
}
在頁面 B(B.html) 上,我希望在頁面 A 上捕獲“Helloworld”并將其列印在頁面 b 上。
console.log(a())
我在 postMessage 上閱讀,但根據我的理解,這僅適用于跨域解決方法的單個頁面上加載的 2 個頁面。
uj5u.com熱心網友回復:
您可以使用瀏覽器的本地存盤功能:localStorage。它有助于將資料作為字串存盤在瀏覽器上。
存盤資料:
localStorage.setItem('foo', 'helloWorld');
獲取保存的資料:
localStorage.getItem('foo');// return 'helloWorld'
uj5u.com熱心網友回復:
我認為sessionStorage符合你的目的。但請注意,當用戶關閉瀏覽器時,資料將被洗掉 - 如果您不希望那樣,只需替換sessionStorage為localStorage. 但是只要您不需要在重新啟動后資料保持不變,您就應該使用sessionStorage不填滿用戶磁盤:
一個.html
window.addEventListener("load", function() { // this is executed when the site is loaded
inputElement = document.getElementById("dataInput");
inputElement.addEventListener("input", function() { // and this whenever the user changes the contents of dataInput
window.sessionStorage.setItem("dataInput", inputElement.value());
});
});
<input id="dataInput" type="text" placeholder="Enter your data">
b.html
window.addEventListener("load", function() {
outputElement = document.getElementById("dataOutput");
outputElement.setText(window.sessionStorage.getItem("dataInput"));
});
<p id="dataOutput">The data should appear here</p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/352576.html
標籤:javascript
下一篇:如何計算值中相同的文本
