javascript - 选择选择选项时显示多个文本
问题描述
我有多个 div,当我选择值 1 时,我想显示 2 个隐藏文本,当我选择值 2 时,它将显示 4 个隐藏文本等。
function showDiv(divId, element) {
document.getElementById('depositProductType').addEventListener('change', function() {
var style = this.value == 1 ? 'block' : 'none';
document.getElementById('allowJoint').style.display = style;
document.getElementById('allowTransfer').style.display = style;
var style = this.value == 2 ? 'block' : 'none';
document.getElementById('allowJoint').style.display = style;
document.getElementById('allowTransfer').style.display = style;
document.getElementById('allowDisabling').style.display = style;
document.getElementById('createOne').style.display = style;
var style = this.value == 3 ? 'block' : 'none';
document.getElementById('allowTransfer').style.display = style;
document.getElementById('createOne').style.display = style;
});
}
<select id="depositProductType" name="prod_type" onchange="showDiv('allowJoint','allowTransfer','allowDisabling','createOne', this)">
<option class="blank" value="">Please select</option>
<option value="1">Fixed Deposit</option>
<option value="2">Savings Deposit</option>
<option value="3">Scheduled Deposit</option>
</select>
<!-- this is the multiple div I want to display from my html -->
<div id="allowJoint"> ------- </div>
<div id="allowTransfer"> ------ </div>
<div id="allowDisabling"> ------- </div>
<div id="createOne"> ---------- </div>
解决方案
首先将您选择的更改为仅传递元素
<select id="depositProductType" name="prod_type" onchange="showDiv(this)">
然后你 showDiv 就不需要监听事件了,因为它已经被 onChange 事件触发了。只需调用您的函数。
function showDiv(ele) {
var allowJoint = document.getElementById('allowJoint');
var allowTransfer = document.getElementById('allowTransfer');
var allowDisabling = document.getElementById('allowDisabling');
var createOne = document.getElementById('createOne');
if(ele.value == 1) {
allowJoint.style.display = 'block';
allowTransfer.style.display = 'block';
allowDisabling.style.display = 'none';
createOne.style.display = 'none';
}
else if(ele.value == 2) {
allowJoint.style.display = 'block';
allowTransfer.style.display = 'block';
allowDisabling.style.display = 'block';
createOne.style.display = 'block';
}
else if(ele.value == 3) {
allowTransfer.style.display = 'block';
createOne.style.display = 'block';
allowJoint.style.display = 'none';
allowDisabling.style.display = 'none';
}
}
推荐阅读
- arrays - 如何循环多维数组
- python - 如何在熊猫数据框中使用应用时创建列时间戳?
- css - css链接可以触发过渡吗?
- spring-integration - Spring路由inputChannel时第一个channel总是出错
- android - 我是否需要 CryptoObject 对象,或者在 FingerprintManager.authenticate 期间对于以下用例为 null
- ansible - Ansible WinRM 仅适用于组中 5 台主机中的 2 台主机
- apache - 如何从 PKCS#7 生成 .key 和 .crt
- arrays - (整数)切片索引作为结构数组
- django - “需要一个有效的文件名!” xhtml2pdf 与 Django
- android - 在 RecyclerView 项目按钮 OnClick 中使用共享首选项