[英]how to get a URL parameter and set the value of a select option on page load?
我是 Javascript 的新手,我在网上找不到一个简单的例子。
我有一个简单的 HTML 页面,上面有一个 select 小部件:
<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
...并在页面加载时在小部件中选择了值?
Set up a change
event handler on the select
and append the querystring (that has the value
of the select
concatenated on to it) to the current 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.