我正在编写一个简单的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,即第一个值。
发布于 2017-10-11 14:09:57
这一行有错误。
document.getElementById("myBtn").addEventListener("click", myFunction());用下面的线代替它。
document.getElementById("myBtn").addEventListener("click", myFunction);
应该在事件侦听器上提到函数引用,但是您是从那里调用它的。
https://stackoverflow.com/questions/46690145
复制相似问题