gpt4 book ai didi

javascript - 如何使用 JavaScript 跳转到特定页面的某个下拉菜单的特定值?

转载 作者:行者123 更新时间:2023-12-01 03:19:32 25 4
gpt4 key购买 nike

假设我们有一个像“Page2.html”这样的下拉菜单:

Page2.html

<div id="myDropDownLink">
<select id="first-drop" name="first-drop">
<option value="Select a State">Select a Steate</option>
<option value="NY">New York</option>
<option value="NJ">New Jersey</option>
</select>
</div>

现在,从“Page1.html”,我们有一个类似的链接

Page1.html

<a href="abc.html" id="mylink">go to page 1</a>

所以目标是:

单击该链接后,它将转到“Page2.html”,然后选择第二个下拉值并被选中。例如,它将选择第二个下拉值,即“NJ”之一。我们可以通过编程来完成吗?

我可以转到特定的页面下拉位置。但我未能从下拉列表中选择第二个值。

window.location.href = forwardedWebsiteLink + "?" + "#first-drop";

知道哪个可以做到这一点吗?

最佳答案

您可以结合两件事:URI anchor (在 uri 中添加 #)和 GET 参数(? 后跟值)来制作类似 example 的内容。 com#first-drop?firstDropDown=nj

在 JavaScript 中(在 page2.html 上),您所要做的就是这样:

//Run the script on page load.
window.onload = function() {
var url = window.location.href;

//Let me cheat since we don't have page1 and page2 in this example...
url += "#firstDropDown?firstDropDown=ny";

// Select the text after the # and before the ? symbol.
var dropDown = url.substring(url.indexOf('#') + 1, url.indexOf('?') - 1);

// Select the text after the ? symbol
var selectedOption = url.substring(url.indexOf('?') + 1);

// Filter the dropdown's ID and its value into an object.
selectedOption = {
elem: selectedOption.substring(0, selectedOption.indexOf('=')),
value: selectedOption.substring(selectedOption.indexOf('=') + 1)
};

// Get the dropdown DOMElement in the page so we can change the selectedIndex.
dropDown = document.querySelector('#' + selectedOption.elem);

var index = 0, selectedIndex = 0;

// Loop through dropDown's children element to find the right one.
dropDown.childNodes.forEach(function(elem, i) {
// Make sur to look for DOMElement nodes only.
if (elem.nodeType == 1) {

if (elem.value === selectedOption.value) {
elem.setAttribute("selected", "selected");
selectedIndex = index;
return true;
}
index++;
}
});
// Now that we have the right index, let's make sure it's selected.
dropDown.selectedIndex = selectedIndex;
}
<select id="firstDropDown">
<option value="nj">New Jersey</option>
<option value="ny">New York</option>
<option value="la">Los Angeles</option>
</select>

运行代码片段将选择纽约作为城市。

关于javascript - 如何使用 JavaScript 跳转到特定页面的某个下拉菜单的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45311791/

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