Javascript-onchange函数只在html select中工作一次(第一次更改后)

Javascript - onchange function only works once (after first change) with html select

本文关键字:一次 函数 第一次 html select Javascript-onchange 工作      更新时间:2023-09-26

我希望以下函数根据用户选择的客户类型显示不同的html输入。

以下代码只运行一次(当选择第一个选项时)

这是我的html:

<select name="customerType" id="customerType" onchange="return customerTypeFunction()">
    <option value="">Customer Type?</option>
    <option value="nonCorp">Customer</option>
    <option value="corp">Corporate</option>
</select>
<div id="nonCorpCustDetails" class="custDetails">
    Forename <input type="text" name="forename" id="forename"/>
    Surname <input type="text" name="surname" id="surname"/>
</div>
<div id="corporateCustDetails" class="custDetails" style="visibility:hidden">
    Company Name <input type="text" name="companyName" id="companyName"/>
</div>

这是我的javascript函数:

function customerTypeFunction() {
    var customerTypeSelect = document.getElementById("customerType").value;
    var corpCustomer = document.getElementById("corporateCustDetails");
    var nonCorpCustomer = document.getElementById("nonCorpCustDetails");
    if ( customerTypeSelect = 'nonCorp') {
        corpCustomer.style.visibility = "hidden";
        nonCorpCustomer.style.visibility = "visible";
    }
    if ( customerTypeSelect = 'corp' ) {
        corpCustomer.style.visibility = "visible";
        nonCorpCustomer.style.visibility = "hidden";
    }
}

=是赋值,==/===是比较。更改if语句以反映这一点。

if (customerTypeSelect === 'nonCorp') {    
    corpCustomer.style.visibility = "hidden";
    nonCorpCustomer.style.visibility = "visible";    
}
if (customerTypeSelect === 'corp') {   
    corpCustomer.style.visibility = "visible";
    nonCorpCustomer.style.visibility = "hidden";   
}

jsFiddle此处