我是 Javascript 新手,在网上找不到简单的例子。
我有一个简单的 HTML 页面,上面有一个选择小部件:
<select name="myProduct">
<option value="aaa">This is AAA</option>
<option value="bbb">This is BBB</option>
<option value="ccc">This is CCC</option>
</select>
Run Code Online (Sandbox Code Playgroud)
像这样将参数传递给 URL 的简单方法是什么......
/mypage.html?selectedProduct=CCC
Run Code Online (Sandbox Code Playgroud)
...并且在页面加载时在小部件中选择了值?
change在 上设置一个事件处理程序select,并将查询字符串(其上连接有 )附加到当前 URL value。select
var urlParams = new URLSearchParams(window.location.search);
let queryString = urlParams.get('selectedProduct');
// Find the option in the select that has the same value as
// the query string value and make it be selected
document.getElementById("myProduct").querySelector("option[value='" + queryString + "']").selected = true;Run Code Online (Sandbox Code Playgroud)
<select id="myProduct">
<option value="aaa">This is AAA</option>
<option value="bbb">This is BBB</option>
<option value="ccc">This is CCC</option>
</select>Run Code Online (Sandbox Code Playgroud)