首页 > 解决方案 > 选择选择选项时显示多个文本

问题描述

我有多个 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>

标签: javascript

解决方案


首先将您选择的更改为仅传递元素

<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';
    }
}

推荐阅读