gpt4 book ai didi

javascript - onclick 事件未在 HTML 上运行选择下拉

转载 作者:太空宇宙 更新时间:2023-11-04 13:58:32 25 4
gpt4 key购买 nike

我当前有一个HTML选择下拉列表,其中六个选项要实现的只是选择“其他”选项时出现JavaScript警报,但是由于某些原因,我无法使此功能工作。

我尝试将 onclick 移动到 select 标签而不是 option 标签,并将警报移到参数之外,这允许它在单击下拉列表时立即出现,这有效但不是我想要的努力实现。

function otherPayment() {
var paymentType = document.getElementById("paymentType").value;
if (paymentType == "Other") {
alert("test");
}
}
<div class="form-group">
<label for="paymentType">Payment Type:</label>
<select class="form-control" id="paymentType" name="paymentType" required>
<option value="">-</option>
<option value="Payment (Initial)">Payment (Initial)</option>
<option value="Payment (Full)">Payment (Full)</option>
<option value="Payment (Balance)">Payment (Balance)</option>
<option value="Delivery Fee">Delivery</option>
<option onclick="otherPayment()" value="Other">Other</option>
</select>
</div>

最佳答案

<option>元素的行为不像普通的 HTML 元素,所以 onclick什么都不做。

最简单的方法是使用 onchange选择的事件,然后检查新选择的元素,如下所示:

function handlePaymentChange(event) {
var paymentType = event.target.value;
if (paymentType == "Other") {
alert("test");
}
}
<div class="form-group">
<label for="paymentType">Payment Type:</label>
<select class="form-control" id="paymentType" name="paymentType" required onchange="handlePaymentChange(event)">
<option value="">-</option>
<option value="Payment (Initial)">Payment (Initial)</option>
<option value="Payment (Full)">Payment (Full)</option>
<option value="Payment (Balance)">Payment (Balance)</option>
<option value="Delivery Fee">Delivery</option>
<option value="Other">Other</option>
</select>
</div>

关于javascript - onclick 事件未在 HTML 上运行选择下拉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54404235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com