我的 php 中有这样的代码:
<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type:
<select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
这些是必须根据所选选项更改其可见性的 div:
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
我试过这个javascript:
<script>
document.getElementsByName("customerType").onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};
</script>
但是 div tradecustdetails"
没有出现并且 div retCustDetails
仍然在那里。
有人能帮忙吗?
最佳答案
getElementsByName()
返回文档中具有指定名称的所有元素的集合。因此你必须像这样遍历它们:
var x = document.getElementsByName("customerType");
for (var i = 0; i < x.length; i++) {
// do something with x[i]
}
如果您只使用一个选择元素,那么最好像这样使用 getElementById()
:
HTML
<select id="customerType" name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
脚本
document.getElementById("customerType").onchange = function () {
var val = this.options[this.selectedIndex].value;
document.getElementById("tradeCustDetails").style.visibility = (val == "trd") ? "visible" : "hidden";
document.getElementById("retCustDetails").style.visibility = (val == "trd") ? "hidden" : "visible";
};
关于javascript - 在 dropbox 中更改选项时更改 div 的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445735/