我希望两个选择字段记住页面重新加载和设置参数时选择的内容。我找到了加载data-url
的解决方案,但是没有找到加载javascript:setParam
的解决方案。
代码的核心来自于这个问题How to add a parameter to the URL?,但做了一些修改。
以下是选择字段:
<select onchange="location = this.value;">
<option value="">Choose a Magic Power</option>
<option value="javascript:setParam('tex_magic_powers','high')">Magic Powers: High</option>
<option value="javascript:setParam('tex_magic_powers','low');">Magic Powers: Low</option>
</select>
<select onchange="location = this.value;">
<option value="">Choose a Strength</option>
<option value="javascript:setParam('tex_strength','average')">Average</option>
<option value="javascript:setParam('tex_strength','mighty');">Mighty</option>
</select>
和脚本:
function setParam(name,value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for (var r = x.exec(s); r; r = x.exec(s)) {
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/** Check to see if the param exist already
Delete if it exist,set it,if it doesn't
**/
if (params[name] && value == params[name]) {
delete params[name];
} else if (params[name] && value != params[name]) {
delete params[name];
params[name] = encodeURIComponent(value);
} else {
params[name] = encodeURIComponent(value);
}
/* set param */
/* build search */
var search = [];
for (var i in params) {
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */``
l.search = search;
}
我以为我在https://webdesign.tutsplus.com/tutorials/dropdown-navigation-how-to-maintain-the-selected-option-on-page-load--cms-32210上找到了代码,但是我不知道在脚本中将其修改为javascript:setParam
而不是data-url
:
HTML:
<select class="myselect">
<option data-url="index.html">All</option>
<option data-url="animals.html">Animals</option>
<option data-url="cars.html">Cars</option>
<option data-url="motorcycles.html">Motorcycles</option>
<option data-url="plants.html">Plants</option>
</select>
脚本:
const select = document.querySelector(".myselect");
const options = document.querySelectorAll(".myselect option");
// 1
select.addEventListener("change",function() {
const url = this.options[this.selectedIndex].dataset.url;
if(url) {
localStorage.setItem("url",url);
location.href = url;
}
});
// 2
if(localStorage.getItem("url")) {
for(const option of options) {
const url = option.dataset.url;
if(url === localStorage.getItem("url")) {
option.setattribute("selected","");
break;
}
}
}