[英]How to set dropdown list value with the value of a link by clicking that link in Javascript
[英]How to set a value for a dropdown list with a value from URL by clicking on a link
我正在尝试通过单击链接(指向同一页面的链接)为下拉列表设置值,并且我想要为select设置的值在链接中。
我试图用这种方法来做,但是因为搞砸了,所以没有用。
这是我使用的代码:
<html>
<body>
<select id="select">
<option value="one">Pen</option>
<option value="two">Paper</option>
<option value="three">Book</option>
</select>
<a class="link1" href="page.php?cc=three">Set select value</a>
<script>
function $_GET(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
var cc = $_GET('cc');
var elmnt = document.getElementsByClassName('link1'),
selectClasse = document.getElementById('select');
function setSelect () {
for (var i = 0; i < elmnt.length; i++) {
elmnt[i].onclick = function () {
selectClasse.value = cc;
}
window.history.pushState('Form', 'My form', this.getAttribute("href"));
return false;
};
}
}
setSelect ();
</script>
</body>
</html>
任何帮助将非常感激。
如果你想用链接及其url参数做到这一点;
根据答案: https : //stackoverflow.com/a/979996/2956448
所以你可以这样做;
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
var cc = params.cc;
var element = document.getElementById('select');
element.value = cc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.