Change class of element using javascript

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers
  • Add class to element 4 answers

  • You have to wrap X in a <td> :

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

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

    Also you have to add case in front of "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:

    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.


    尝试这个

    switch(value){
        case "a": document.getElementById("x").setAttribute("class", show); break;        
        case "b": document.getElementById("x").setAttribute("class", hide); break;
    }
    
    链接地址: http://www.djcxy.com/p/25202.html

    上一篇: 如何在Javascript中设置元素的类属性?

    下一篇: 使用javascript更改元素的类