使用javascript在html中基于下拉选择显示和隐藏div元素

时间:2015-05-06 15:26:47

标签: javascript html select

我有一个问题,使用javascript来显示使用下拉列表时隐藏div。代码适用于链接和按钮,但我问是否有任何方法可以重写它,以便它可以使用SELECT选项。就像我选择'显示'从下拉列表中,它会显示包含“Hello world!”的div。'

我目前的Javascript:

<script>
function showMe(id) {
    var e = document.getElementById(id);
    if(e.style.display == "block") {
        e.style.display = "none";
    } else {
        e.style.display = "block";
    }
}
</script>

index.html包含:

<select>
    <option>Hide</option>
    <option onselect="showMe('idShowMe')">Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>

4 个答案:

答案 0 :(得分:4)

您可以更改代码

&#13;
&#13;
function showMe(e) {
    var strdisplay = e.options[e.selectedIndex].value;
    var e = document.getElementById("idShowMe");
    if(strdisplay == "Hide") {
        e.style.display = "none";
    } else {
        e.style.display = "block";
    }
}
&#13;
<select onchange="showMe(this);">
    <option>Hide</option>
    <option>Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

    <select onchange="showMe(this)">
    <option>Hide</option>
    <option >Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>



function showMe(selectedOption) {

    if(selectedOption.value=="Hide") {
        document.getElementById('idShowMe').style.display = 'none';
    } else {
        document.getElementById('idShowMe').style.display = 'block';
    }
}

答案 2 :(得分:1)

这可以通过onchange事件完成,然后检查所选选项。 http://jsfiddle.net/hanno_drefke/dwfr224q/

Javascript 代码:

var current;
function showMe(element) {
  if(current!==undefined){
    document.getElementById(current).setAttribute('style','display:none');
  }
  var fetchMe = element.options[element.selectedIndex].getAttribute('data-show');
  if(fetchMe!==null){
    document.getElementById(fetchMe).setAttribute('style','display:block'); 
    current=fetchMe;
  }
}

对您的 HTML 代码进行微小更改:

<select onchange="showMe(this)">
    <option>Hide</option>
    <option data-show="idShowMe">Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>

使用此解决方案可以自由地将具有相应id的任何层连接到该选项。只需插入数据显示值并创建一个id为div的div: http://jsfiddle.net/hanno_drefke/dwfr224q/1/

答案 3 :(得分:1)

JS Fiddle用于相同的

<select id="mySelect" onchange="showMe('idShowMe')">
    <option>Hide</option>
    <option>Show</option>
</select>

<div id="idShowMe" style="display: none">
    <b>Hello world!</b>
</div>

<script>
function showMe(id) {
    var e = document.getElementById(id);
    if(e.style.display == "block") {
        e.style.display = "none";
    } else {
        e.style.display = "block";
    }
}
</script>