选择下拉值始终指向0索引

时间:2017-10-11 13:58:48

标签: javascript html5 drop-down-menu getelementbyid getelementsbytagname

我正在编写一个简单的JavaScript代码来检索所选项的值,它总是指向0索引并给我第一个值。

HTML代码

<html>
    <head>
    <title>Simple Extension</title>
    </head>
    <body>
        Select a web page
        <select id="mySelect">
            <option value="uc4_scriptGuide">UC4 Script Guide</option>
            <option value="uc4_docu">UC4 Documentation</option>
            <option value="allSec">Pay Role</option>
            <option value="myte">Time Sheets</option>
        </select>
        <button type="button" id="myBtn">Go There</button>
    <script src="background.js"></script>
    </body>
</html>

JavaScript代码

document.getElementById("myBtn").addEventListener("click", myFunction());

function myFunction() {
    var item = document.getElementById("mySelect").selectedIndex;
    console.log(document.getElementsByTagName("option")[item].value);
}

输出始终是uc4_scriptGuide,即第一个值。

1 个答案:

答案 0 :(得分:2)

这条线错误就是

document.getElementById("myBtn").addEventListener("click", myFunction());

将其替换为以下行。

document.getElementById("myBtn").addEventListener("click", myFunction);

我应该在事件监听器上提到函数引用,但是你从那里调用它。

相关问题