使用javascript更改元素的类

sha*_*era 0 javascript html-select onchange

我很难根据select标签中的选定项目更改元素类.这是我的代码:

<table> 
    <tr>
        <select onchange="wow(this.value)">
            <option value="a">a</option>
            <option value="b">b</option>            
        </select>
    </tr>               
    <tr id="x" class="show">
        x
    </tr>
</table>

<script>
function wow(value){
    switch(value){
        case "a": document.getElementById("x").className = "show"; break;       
        case "b": document.getElementById("x").className = "hide"; break;
    }
}
</script>

<style>
.show{
    display:inline-block;
}

.hide{
    display:none;
}
</style>
Run Code Online (Sandbox Code Playgroud)

我在这里没有看到任何问题.我也试过setAttribute("class", "show")但不行.

Der*_*會功夫 7

你必须包装X<td>:

http://jsfiddle.net/DerekL/CVxP7/

<tr>...<td id="x" class="show">x</td></tr>
Run Code Online (Sandbox Code Playgroud)

你也必须case在前面添加"a":

case "a":
    document.getElementById("x").setAttribute("class", "show");
    break;
Run Code Online (Sandbox Code Playgroud)

PS:有一种更有效的方法来实现你想要做的事情:

http://jsfiddle.net/DerekL/CVxP7/2/

function wow(value) {
    var index = {
        a: "show",
        b: "hide"
    };
    document.getElementById("x").setAttribute("class", index[value]);
}
Run Code Online (Sandbox Code Playgroud)

现在您不需要输入document.getElementById("x").setAttribute("class"...两次.