如何获取URL参数并在页面加载时设置select选项的值



我是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>

将参数传递到URL的简单方法是什么。。。

/mypage.html?selectedProduct=CCC

并在页面加载时在小部件中选择值?

select上设置一个change事件处理程序,并将查询字符串(连接了selectvalue(附加到当前URL。

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;
<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>

我让它像这样工作。。。

<html>
<head>
/* .... */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(function() {
var selectedProduct = GetURLParameter("selectedProduct");
if (selectedProduct) {
$("#myProduct").val(selectedProduct); 
}
});

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
</script>
<body>
<select id="myProduct"> <!-- NOTE that's 'id', not 'name' there -->
<option value="aaa">This is AAA</option>
<option value="bbb">This is BBB</option>
<option value="ccc">This is CCC</option>
</select>
</body
</html>

最新更新