我找到了一个带有按钮重定向代码的自定义选择下拉列表。它适用于一个下拉菜单,但我想制作两个下拉菜单。 我尝试为 select-id2 添加 var,但脚本停止工作并且没有任何反应。
<select id="select-id1">
<option value="" selected="">First category</option>
<option value="http://example.com">Example</option>
</select>
<select id="select-id2">
<option value="" selected="">Second category</option>
<option value="/page">Page</option>
</select>
<button onclick="siteRedirect()">GO</button>
<script>
function siteRedirect() {
var selectbox = document.getElementById("select-id");
var selectedValue = selectbox.options[selectbox.selectedIndex].value;
window.location.href = selectedValue;
}
</script>
第一个 (select-id1) 应具有域 example.com,第二个 (select-id2) 应在第一个上添加/page。所以重定向链接应该是 example.com/page。
有什么办法可以处理这个代码吗?
最佳答案
您正在搜索 id="select-id"
的元素。当仅存在 select-id1
和 select-id2
时。
试试这个:
function siteRedirect() {
var select1 = document.querySelector("#select-id1"),
select2 = document.querySelector("#select-id2");
var category = select1.options[select1.selectedIndex].value,
subcategory = select2.options[select2.selectedIndex].value;
redirect = category+subcategory;
console.log("Redirect to: "+redirect);
}
<select id="select-id1">
<option value="" selected="">First category</option>
<option value="http://example.com">Example</option>
</select>
<select id="select-id2">
<option value="" selected="">Second category</option>
<option value="/page">Page</option>
</select>
<button onclick="siteRedirect()">GO</button>
关于javascript - 多个下拉菜单重定向到 URL ( HTML ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261814/