如何添加锚href属性到选项对象?

时间:2019-06-20 07:56:24

标签: javascript html

我正在尝试在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>

1 个答案:

答案 0 :(得分:1)

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

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

}