if语句没有在javascript中执行[always else]

时间:2014-06-18 21:48:13

标签: javascript

请任何一个帮助。总是返回其他..我想要的是,当选择第一个下拉列表时,第二个下拉隐藏和副Versa

HTML

<form id="myform" onchange="check();" >

<select id="myselecta" >
 <option value="a1">a1</option>
 <option value="a2">a2</option>
</select>

<select id="myselectb" >
    <option value="b1">b1</option>
    <option value="b2">b</option>
</select> 

java脚本

function check() {
    var dropdown = document.getElementById('myform').value;
        if (dropdown == 'myselecta') {
        document.getElementById('myselectb').style.display = 'none';
        }
        else {
            document.getElementById('myselecta').style.display = 'none';
        }
}

3 个答案:

答案 0 :(得分:2)

你想完成这样的事吗?

<强> HTML

<select id="switch" onchange="check();">
 <option value="myselecta">myselecta</option>
 <option value="myselectb">myselectb</option>
</select>

<select id="myselecta">
 <option value="a1">a1</option>
 <option value="a2">a2</option>
</select>

<select id="myselectb">
 <option value="b1">b1</option>
 <option value="b2">b</option>
</select> 

<强> JS

function check() {
    var dropdown = document.getElementById('switch').value;
    if (dropdown === 'myselecta') {
        document.getElementById('myselecta').style.display = 'block';
        document.getElementById('myselectb').style.display = 'none';
    } else {
        document.getElementById('myselecta').style.display = 'none';
        document.getElementById('myselectb').style.display = 'block';
    }
}

修改

HTML

<select id="myselecta" onclick="check()">
 <option value="a1">a1</option>
 <option value="a2">a2</option>
</select>

<select id="myselectb" onclick="check()">
 <option value="b1">b1</option>
 <option value="b2">b</option>
</select>

的javascript

function check() {
    if (this.id === 'myselecta') {
        document.getElementById('myselectb').style.display = 'none';
    } else {
        document.getElementById('myselecta').style.display = 'none';
    }
}

答案 1 :(得分:1)

尝试更改

var dropdown=document.getElementById('myform').value;

var dropdown=document.getElementById('myform').getAttribute('id');

答案 2 :(得分:0)

据我所知,onchange事件不会捕获单个select的onchange事件。您最好为每个单独的select元素添加一个onchange,并将一个参数传递给该函数,就像元素的ID一样,以区分触发事件的元素。