您可以使用select 元素中的model 属性轻松获取值。
首先像这样添加一个onclick函数
<input type="submit" name="submit" value="Submit" onclick="getValues()"/>
然后获取按钮提交时的值(完整代码)Plunkr
我查看了您的代码,设置选择框渲染的方式我们必须显式调用 updateSelect() 函数才能使选项正常工作。此功能使您的选择框“动态”。
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");
if(first !== null && second !== null && third !== null) {
setValues(); //this should come after getting the values above
}
function getValues() {
var first = document.getElementsByTagName("SELECT")[0].getAttribute("model");
var second = document.getElementsByTagName("SELECT")[1].getAttribute("model");
var third = document.getElementsByTagName("SELECT")[2].getAttribute("model");
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
}
//on load when this function is called globally, the values from the localStorage will be set to the dropdown values.
function setValues() {
//for first dropdown
document.getElementsByTagName("SELECT")[0].setAttribute("model", first);
document.getElementsByTagName("SELECT")[0].value = first;
updateSelect(document.getElementsByTagName("SELECT")[0]);
//for second dropdown
document.getElementsByTagName("SELECT")[1].setAttribute("model", second);
document.getElementsByTagName("SELECT")[1].value = second;
updateSelect(document.getElementsByTagName("SELECT")[1]);
//for third dropdown
document.getElementsByTagName("SELECT")[2].setAttribute("model", third);
document.getElementsByTagName("SELECT")[2].value = third;
updateSelect(document.getElementsByTagName("SELECT")[1]);
}
要保留价值,您别无选择,只能像这样使用window.localStorage -
localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);
然后取值
var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");