如何在 javascript onClick 中使用本地存盤中的資料。我在下面有我的 html 檔案和 javascript 檔案。謝謝
<fieldset>
<form>
<!--GET USER NAME-->
<p>
<label for="inName" >What is your name?</label>
<input type="text" id="inName" name="f_name"/>
</p>
<!-- GET COLOUR--> // I m not sure about how the get color as user can
//choose the color from drop down color palet.
<p>
<label for="inColor" >What is your favourite colour? </label>
<input type="color" id="inColor" name="f_color" />
</p>
<p> // how to get the value when user clicks the button
// in order to call onClick function to output the
user's name and
// display favorite color in background.
<input type="submit" value="Click to save" />
<p/>
</fieldset>
</form>
當用戶單擊提交表單時,我不知道如何從本地存盤中獲取資料:
//NOW THAT WE HAVE STORED DATA ON ONE PAGE, WE CAN ACCESS IT FROM ANY PAGE ON THIS
WEBSITE.
window.onload = function(){
//GET ELEMENTS USED FOR OUTPUT
var userOut = document.getElementById("newMsgBox");
//GET VALUES FROM COOKIES/LOCAL STORAGE
var userName = localStorage.getItem("nameIn");
var userColor = localStorage.getItem("inColor");
//CREATE OUTPUT WITH VALUES
if (userName !== null) {
userOut.innerHTML = " " userName;
}
}//end onl oad
uj5u.com熱心網友回復:
如果您想從特定按鈕監聽事件,然后訪問您的 localStorage,您可以這樣做:
首先獲取元素:
const button = document.getElementById('<clickable_element_id>');
然后為按鈕添加一個監聽器;
button.addEventListener("click",(event)=> {
event.preventDefault() // only if you want to prevent the action
//here you can access to your local store items like:
const a = localStorage.getItem("<item you saved previously>");
...
});
uj5u.com熱心網友回復:
真的不清楚你想做什么,但是
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inColor');
將為您獲取值。我想你正在尋找這樣的東西。
<script>
function saveData() {
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inName');
localStorage.setItem("inColor", inColor);
localStorage.setItem("inName", inName);
}
</script>
<input type="Button" value="Click to save" onclick="saveData"/>
uj5u.com熱心網友回復:
匯入 Jquery 并使用它。我希望能幫助你。當您單擊 id 為 idOfBtn 的按鈕時,jquery 將彈出事件并使用鍵(鍵)呼叫 localStorage。將其替換為您的密鑰名稱。
$("#idOfBtn").click(function() {
alert(localStorage.getItem('_key_'));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461597.html
標籤:javascript
上一篇:在React中編輯多個輸入欄位
