Onchange show div,隐藏之前选择的

时间:2015-04-07 13:16:52

标签: javascript html forms

我有一个脚本,可以从州和城市中选择商店,并在不同的div中显示它们。我遇到的问题是,当选择另一个城市时,前一个div仍会显示,但它们应该被隐藏。这是我的剧本:

function showStores(state)
    {
        if (state == 'SS')
        {
            document.getElementById(document.getElementById('citySS').value).style.display = '';
            document.getElementById('citySS').selectedIndex = 0;    
        }

        else if (state == 'ZZ')
        {
            document.getElementById(document.getElementById('cityZZ').value).style.display = '';
            document.getElementById('cityZZ').selectedIndex = 0;    
        }
    }
        <form>
    <select onchange="javascript:showStores('SS');" id="citySS" name="citySS">
                <option selected>-</option>
                <option value="city1">city 1</option>
                <option value="city2">city 2</option>
    </select>

    <select onchange="javascript:showStores('ZZ');" id="cityZZ" name="cityZZ">
                <option selected>-</OPTION>
                <option value="city3">city 3</option>
                <option value="city4">city 4</option>

    </select>           
    </form>

    <div id="city1" style="display: none">
    content 1
    </div>

    <div id="city2" style="display: none">
    content 2
    </div>

    <div id="city3" style="display: none">
    content 3
    </div>

    <div id="city4" style="display: none">
    content 4
    </div>

http://jsfiddle.net/6h9mLw6f

感谢您的帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

对于您希望显示/隐藏的每个div,您可以指定类属性,如下所示:

<div class="cityClass" id="city1" style="display: none">

接下来,在您的JavaScript中,每当调用showStores()函数时,您应该找到属于类cityClass的所有div并确保它们被隐藏。这是通过首先找到所有这些div来完成的:

var allCities = document.getElementsByClassName("cityClass");

遍历数组以逐一隐藏它们:

for (var i=0; i < allCities.length; i++)
{
    allCities[i].setAttribute('style','display: none');
}