gpt4 book ai didi

javascript - 如何通过单击链接使用来自 URL 的值来设置下拉列表的值

转载 作者:行者123 更新时间:2023-11-28 06:14:00 33 4
gpt4 key购买 nike

我试图通过单击链接(指向同一页面的链接)来设置下拉列表的值,并且我要为选择设置的值位于链接中。
我尝试这样做,但因为它搞砸了,所以没成功。
这是我使用的代码:

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

关于javascript - 如何通过单击链接使用来自 URL 的值来设置下拉列表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132470/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com