![](/img/trans.png)
[英]open a long <select> dropdown to specific option when the dropdown is first clicked
[英]Dropdown select reloads to first option when reloaded
您好,我在使用 select 下拉菜單時遇到問題。 我正在嘗試存儲該值,但它不起作用。 我已經看過其他問題了,但沒有運氣。
這是一個小提琴:
function selectCss(element) { const a = element.options[element.selectedIndex].value; document.getElementById("change").onchange = function() { localStorage['colorPick'] = element.options[element.selectedIndex].value; } window.onload = function() { if (localStorage['colorPick']) document.getElementById("change").value = localStorage['colorPick']; } if (a == "Theme 1") { document.body.style.background = "pink"; } if (a == "Theme 2") { document.body.style.background = "blue"; } if (a == "Theme 3") { document.body.style.background = "yellow"; } }
body { background: pink; }
<select id="change" name="colorPick" onchange="selectCss(this)"> <option selected value="Theme 1">Theme 1</option> <option value="Theme 2">Theme 2</option> <option value="Theme 3">Theme 3</option> </select>
代碼有幾個問題:
localStorage
中有項目,則應設置select
的值和color
。 這應該首先完成,而不是在 function 內完成。else-if
而不是將值比較三遍。html
元素中設置onchange
,因此不應在 function 中聲明它。select.value
獲取所選值,其中 select 是此示例中的html
元素經過適當修改的工作解決方案如下:
let select = document.getElementById("change") if (localStorage['colorPick']){ select.value = localStorage['colorPick']; selectCss(); } function selectCss() { const a = select.value; localStorage['colorPick'] = a; if (a == "Theme 1") { document.body.style.background = "pink"; }else if (a == "Theme 2") { document.body.style.background = "blue"; }else if (a == "Theme 3") { document.body.style.background = "yellow"; } }
body {background: pink;}
<select id="change" name="colorPick" onchange="selectCss()"> <option selected value="Theme 1">Theme 1</option> <option value="Theme 2">Theme 2</option> <option value="Theme 3">Theme 3</option> </select>
使用 setItem 方法來存儲到本地存儲。
localStorage.setItem("colorPick", element.options[element.selectedIndex].value);
使用 getItem 方法檢索
讓 colorPick = localStorage.getItem("colorPick")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.