如何在 JavaScript 的 OnChange() 事件中使用 If Else?

How to use If Else in OnChange() event in JavaScript?

这是我的 HTML 代码:

<select id="stand" onchange="myFun2()">
                <option value="platinumGallery">Platinum Gallery</option>
                <option value="superHospitalityStand">Super Hospitality Stand</option>
                <option value="northWestStand">North West Stand</option>
                <option value="eastStand">East Stand</option>
</select><br><br>

<label>Cost Of Ticket: </label>
<input id="costOfTicket" type="text" readonly>

和JS代码:

function myFun2(){
    var costOfTicket;
    var selectedStand = document.getElementById("stand").value;
    if(selectedStand = "platinumGallery"){
        costOfTicket = 25000;
    }
    else if(selectedStand = "superHospitalityStand"){
        costOfTicket = 20000;
    }
    document.getElementById("costOfTicket").value = costOfTicket;
}

每当onchange()事件发生我想根据select的选择值显示Cost Of Ticket。但是它在 onchange() 事件之后显示 25000 然后无论选择的值如何都不会改变。如何更正代码以完成上述任务?

让我告诉你。在 if-else 语句中,您没有比较值,但实际上,您正在 分配 值。

因此将您的 if-else 语句更改为:

if(selectedStand == "platinumGallery"){
        costOfTicket = 25000;
}
else if(selectedStand == "superHospitalityStand"){
        costOfTicket = 20000;
}

您在 if 语句中使用了 =。您需要在 `if 语句中使用 ===== 以使其作为条件起作用。

function myFun2(){
    var costOfTicket;
    var selectedStand = document.getElementById("stand").value;
    
    if(selectedStand == "platinumGallery"){
        costOfTicket = 25000;
    }
    else if(selectedStand == "superHospitalityStand"){
        
        costOfTicket = 20000;
    }
    document.getElementById("costOfTicket").value = costOfTicket;
}
<select id="stand" onchange="myFun2()">
                <option value="platinumGallery">Platinum Gallery</option>
                <option value="superHospitalityStand">Super Hospitality Stand</option>
                <option value="northWestStand">North West Stand</option>
                <option value="eastStand">East Stand</option>
</select><br><br>

<label>Cost Of Ticket: </label>
<input id="costOfTicket" type="text" readonly>