本文介绍了如何通过点击链接为URL中的值设置下拉列表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过点击链接(链接到同一页面)来设置下拉列表的值,并且我想为该选择设置的值位于链接中。
我试图这样做,但因为它搞砸了,它不起作用。
这里是我使用的代码:
I'm trying to set a value for a dropdown list by clicking on a link(links to the same page), and the value that i want to set for the select is in the link.
I tried to do it this way, but because it is messed up it didn't work.
Here's the code i used:
<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>
任何帮助都将不胜感激。
Any help would be much appreciated.
推荐答案
如果你想用链接和它的url参数来做到这一点;
If you want to do this with a link and its url parameters;
根据答案:
所以你可以这样做;
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;
这篇关于如何通过点击链接为URL中的值设置下拉列表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!