<!DOCTYPE html>
<html>
<head>
<title>NYC MTA</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<p>Line N</p>
下拉按钮
<select id ="Select">
<option id="Select">Times Square</option>
<option id="34th">34th</option>
<option id="28th">28th</option>
<option id="23th">23th</option>
<option id="23th">Union Square</option>
<option id="8th">8th</option>
</select>
<select>
<option id="Times Square">Times Square</option>
<option id="34t">34th</option>
<option id="28t">28th</option>
<option id="23t">23th</option>
<option id="23t">Union Square</option>
<option id="8t">8th</option>
</select>
</body>
<script type="text/javascript" src="index.js"></script>
</html>
<script>
window.onload= function(){
var lnListeners = function(){
var ln = document.getElementById("Select");
if(ln){
ln.addEventListener('change', function(){alert("Do great stuff")});
}
lnListeners();
}
};
</script>
答案 0 :(得分:0)
id="Select"
应仅位于<select>
元素中,而不是<option>
元素中。 ID必须是唯一的。
你需要在函数定义之外调用lnListeners
。
window.onload = function() {
var lnListeners = function() {
var ln = document.getElementById("Select");
if (ln) {
ln.addEventListener('change', function() {
alert("Do great stuff")
});
}
};
lnListeners();
};
<select id="Select">
<option id="Times Square">Times Square</option>
<option id="34th">34th</option>
<option id="28th">28th</option>
<option id="23th">23th</option>
<option id="23th">Union Square</option>
<option id="8th">8th</option>
</select>
答案 1 :(得分:0)
在您的情况下,您只需在其范围之外调用函数lnListeners()。
var lnListeners = function(){
var ln = document.getElementById("Select");
if(ln){
ln.addEventListener('change', function(){alert("Do great stuff")});
}
}
lnListeners();
<select id ="Select">
<option id="Select">Times Square</option>
<option id="34th">34th</option>
<option id="28th">28th</option>
<option id="23th">23th</option>
<option id="23th">Union Square</option>
<option id="8th">8th</option>
</select>
<select>
<option id="Times Square">Times Square</option>
<option id="34t">34th</option>
<option id="28t">28th</option>
<option id="23t">23th</option>
<option id="23t">Union Square</option>
<option id="8t">8th</option>
</select>