2013-03-11 198 views
0

我很难根据select标记中的选定项目更改元素的类别。这是我的代码:使用javascript更改元素的类别

<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> 

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

+0

@GlennFerrieLive这是一个jQuery的例子。 – Hamish 2013-03-11 03:53:03

+1

你错过了交换机的'case'部分。 – j08691 2013-03-11 03:54:41

回答

6

你有一个<td>X

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

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

你也需要在前面加case"a":

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

PS:有一个更高效的w唉,实现你正试图在这里做的事:

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

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

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

+0

它的工作原理,谢谢,但为什么我不能把课程放在? – shankshera 2013-03-11 04:03:37

+0

@shankshera - 技术上你可以,但这是一个很好的习惯[用''或'​​'](https://developer.mozilla.org/en-US/docs/HTML/Element/table #例子)。 – 2013-03-11 04:06:36

0

试试这个

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

'show'没有被定义。 – 2013-03-11 04:01:28

+0

show是classname。 – 2013-03-11 04:02:44