select 下拉值始终指向 0 索引
select dropdown value always pointing to 0 index
我正在编写一个简单的 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即第一个值。
好吧,这行错误
document.getElementById("myBtn").addEventListener("click", myFunction());
将其替换为下一行。
document.getElementById("myBtn").addEventListener("click", myFunction);
我应该在事件侦听器中提到函数引用,但你是从那里调用它的。
我正在编写一个简单的 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即第一个值。
好吧,这行错误
document.getElementById("myBtn").addEventListener("click", myFunction());
将其替换为下一行。
document.getElementById("myBtn").addEventListener("click", myFunction);
我应该在事件侦听器中提到函数引用,但你是从那里调用它的。