gpt4 book ai didi

javascript - 如何将 anchor href 属性添加到选项对象?

转载 作者:行者123 更新时间:2023-12-02 23:27:14 25 4
gpt4 key购买 nike

我正在尝试在 HTML 的下拉列表中创建超链接。我能够向下拉列表添加文本,但添加 href 属性对我不起作用。请问有什么建议吗?

<!DOCTYPE html>
<html>
<body onload="loadAgeSelector()">
<select id="yearselect"></select>
<script>
function loadAgeSelector()
{
var startyear = 1900;
var endyear = 2014;
for (var i = startyear;i<=endyear;i++){
node=document.createElement("Option");
textnode=document.createTextNode(i);
node.appendChild(textnode);

var att = document.createAttribute( "href" );
att.value = "https://www.google.com/" ;
node.setAttributeNode(att);
document.getElementById("yearselect").appendChild(node);
}
}
</script>
</body>
</html>

最佳答案

您应该监听更改事件然后处理链接,测试以下代码:

function loadAgeSelector()
{
var select = document.getElementById("yearselect");
var startyear = 1900;
var endyear = 2014;
for (var i = startyear;i<=endyear;i++){
node=document.createElement("Option");
textnode=document.createTextNode(i);
node.appendChild(textnode);
node.value = "https://www.google.com/?testid=" + i;
select.appendChild(node);
}

select.onchange = function () {
var link = this.value;
window.open(link);//or if you want to open in current tab: window.location.href = link;
}

}

关于javascript - 如何将 anchor href 属性添加到选项对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56681500/

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