javascript - 多个下拉菜单重定向到 URL ( HTML )

标签 javascript html html-select

我找到了一个带有按钮重定向代码的自定义选择下拉列表。它适用于一个下拉菜单,但我想制作两个下拉菜单。 我尝试为 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-id1select-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/

相关文章:

javascript - TypeScript 中的扩展如何工作?

javascript - 即使响应成功,firebase 数据库也不会更新

javascript - 使用ajax将jquery变量插入到php中?

jquery - 在 iOS 中打开 HTML 选择元素时是否会触发 DOM 事件?

html - 在 asp.net 下拉列表控件中垂直对齐文本

javascript - Meteor.js android版本代码

javascript - 如何从浏览器获取历史记录等信息并将它们放在 div 元素中

c# - 获取一个页面只能有一个服务器端表单标签错误

html - 使用 :before CSS3 pseudo-selector 使背景图像变暗

javascript - CasperJS : dropdown list; select an option, 代码在浏览器和 slimer 中有效,但在 phantom 中无效