如何在链接后保留所选选项? 我正在使用值作为href,当它加载时它只返回所有。 我该怎么做才能锁定期权价值?
这是我的选择代码:
echo ($AppUI->_("Company tickets:") . '<select id="my-select2" name="currentComp">');
echo ('<option value="?m=ticketsmith"/>All') ;
foreach ($rows as $row) {
if (in_array($row['company_id'], $array1)) {
echo ('<option value="?m=ticketsmith&ticket_company=' . $row['company_id'] . '" />' . $row['company_id'].', ' . $row["company_name"]) ;
}
}
这是我的JS:
document.getElementById("my-select2").onchange = function() {
localStorage.setItem('my-select2', document.getElementById("my-select2").value);
window.location.href=this.value;
}
if (localStorage.getItem('my-select2')) {
document.getElementById("my-select2").options[localStorage.getItem('my-select2')].selected = true;
}
答案 0 :(得分:1)
版本1
document.getElementById("my-select2").onchange = function() {
localStorage.setItem('my-select2', this.value);
window.location.href=this.value;
}
var val = localStorage.getItem('my-select2');
if (val) {
document.getElementById("my-select2")[val].selected=true;
}
第2版(推荐)
window.onload=function() {
document.getElementById("my-select2").onchange = function() {
localStorage.setItem('my-select2', this.selectedIndex);
window.location.href=this.value;
}
var selIdx = localStorage.getItem('my-select2');
if (selIdx !=null && selIdx !=-1) {
document.getElementById("my-select2").selectedIndex=selIdx;
}
}