通过getElementById查找所选索引是't返回正确的值

Finding the selected index by getElementById isn't returning the right value

本文关键字:返回 查找 getElementById 索引 通过      更新时间:2023-09-26

"building"下拉列表的选择应等于零。它在第一个选项上。当选择下拉列表旁边的按钮时,将执行函数search()。由于某种原因,警报返回"它不起作用。"

<script>
var a = document.getElementById("building").selectedIndex;
function search() {
   if (a === 0) {
        window.alert("It worked.");
        event.preventDefault();
   } else {
        window.alert("It didn't work.");
        event.preventDefault();
   }
}              
</script>

这是选择下拉列表。

<form id="apartmentSelection">
<br>    
Building:
<select id="building">
    <option value="all">All</option>
    <option value="1">1</option>  
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
</select>
</form>

这是按钮。

<button onclick="search()">Search</button>

Var a在错误的位置,您不需要event.preventDefault();两次。

function search() {
event.preventDefault();
var a = document.getElementById("building").selectedIndex;
   if(a === 0){
   alert("It worked.");
   } else {
   alert("It didn't work.");     
   }   
}