我有这个在Jsfiddle中运行的JavaScript代码。当用户在下拉列表中选择“是”时,第二个会自动选择“否”,反之亦然。我已将其格式化为我的HTML页面,由于某种原因它不起作用。
我使用chrome作为浏览器。我已经在我的JS中添加了jsfiddle链接以及我的HTML代码。
Jsfiddle Link:https://jsfiddle.net/rk57hkak/10/
HTML CODE:
<!DOCTYPE html>
<html>
<body>
<script src="committee.js"></script>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
<option value="">Select Option</option>
<option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
<option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class="microphone select2" name = "microphone">
<option value=" " selected="selected">Select Option</option>
<option value="ON. Thank you.">ON</option>
<option value="OFF. Thank you.">OFF</option>
</select>
</div>
</body>
</html>
JavaScript代码:
const cmicrophone = document.querySelector('.select1');
const microphone = document.querySelector('.select2');
function inputHandler(thisSelect, otherSelect) {
// console.log(thisSelect.selectedIndex)
if (thisSelect.selectedIndex == 1) {
otherSelect.selectedIndex = 1;
} else if (thisSelect.selectedIndex == 2) {
otherSelect.selectedIndex = 2;
} else {
thisSelect.selectedIndex = 0;
otherSelect.selectedIndex = 0;
}
}
cmicrophone.addEventListener('input', event => {
inputHandler(cmicrophone, microphone);
});
microphone.addEventListener('input', event => {
inputHandler(microphone, cmicrophone);
});
答案 0 :(得分:1)
这是因为脚本在DOM中存在元素之前执行。在这种情况下,行const cmicrophone = document.querySelector('.select1');
&安培;由于元素
const microphone = document.querySelector('.select2');
将失败
<body>
//html code
<script src="committee.js"></script> // Include script here
</body>