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

这是我的 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()事件发生时,我想Cost Of Ticket根据选择的值进行显示select。但它会在事件发生25000后显示onchange(),然后无论选择的值如何都不会改变。如何修正代码来完成上述任务?


翻阅古今
浏览 71回答 2
2回答

尚方宝剑之说

让我告诉你。在 if-else 语句中,您不是在比较值,而是实际上是在分配值。因此,将 if-else 语句更改为:if(selectedStand == "platinumGallery"){&nbsp; &nbsp; &nbsp; &nbsp; costOfTicket = 25000;}else if(selectedStand == "superHospitalityStand"){&nbsp; &nbsp; &nbsp; &nbsp; costOfTicket = 20000;}

慕侠2389804

您在声明=中使用了if。您需要在`if 语句中使用==or===来使其作为条件起作用。function myFun2(){&nbsp; &nbsp; var costOfTicket;&nbsp; &nbsp; var selectedStand = document.getElementById("stand").value;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if(selectedStand == "platinumGallery"){&nbsp; &nbsp; &nbsp; &nbsp; costOfTicket = 25000;&nbsp; &nbsp; }&nbsp; &nbsp; else if(selectedStand == "superHospitalityStand"){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; costOfTicket = 20000;&nbsp; &nbsp; }&nbsp; &nbsp; document.getElementById("costOfTicket").value = costOfTicket;}<select id="stand" onchange="myFun2()">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="platinumGallery">Platinum Gallery</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="superHospitalityStand">Super Hospitality Stand</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="northWestStand">North West Stand</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="eastStand">East Stand</option></select><br><br><label>Cost Of Ticket: </label><input id="costOfTicket" type="text" readonly>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript