javascript 使用javascript更改元素的类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15330894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:24:55  来源:igfitidea点击:

Change class of element using javascript

javascriptonchangehtml-select

提问by shankshera

I'm having difficulties to change class of element based on selected item in selecttag. This is my code:

我在根据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>

I don't see any problem here. I also tried setAttribute("class", "show")but doesn't work.

我在这里看不到任何问题。我也试过,setAttribute("class", "show")但不起作用。

回答by u283863

You have to wrap Xin a <td>:

你必须包裹X在一个<td>

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

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

<tr>...<td id="x" class="show">x</td></tr>

Also you have to add casein front of "a":

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

case "a":
    document.getElementById("x").setAttribute("class", "show");
    break;


PS: There is a more efficient way to achieve what you are trying to do here:

PS:有一种更有效的方法可以实现您在此处尝试执行的操作:

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

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

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

Now you don't need to type document.getElementById("x").setAttribute("class"...twice.

现在您无需键入document.getElementById("x").setAttribute("class"...两次。

回答by Devang Rathod

Try this

试试这个

switch(value){
    case "a": document.getElementById("x").setAttribute("class", show); break;        
    case "b": document.getElementById("x").setAttribute("class", hide); break;
}