2012-08-04 100 views
1

我會盡我所能解釋它。我使用Javascript中的按鈕(紅色右側),所以當我點擊每個按鈕時,它們變成綠色,當我再次點擊它們時,它們變成紅色。我試圖讓圖像按鈕(左側)工作,如果我點擊每一個它會轉動javascript按鈕(紅色右側)。這意味着我可以使用任何一個來啓用/禁用。image to javascript button

這裏是圖像:

Image for buttons

HTML代碼:

<img src="images/menuIcons/skip.gif" width="126" height="34" /> 
    <div align="center" style="margin-bottom: 10px; margin-left: 10px;"> 
     <button id="skip" class="red" onclick="controls(this.getAttribute('class'),this.id)"></button> 

<img src="images/menuIcons/text.gif" width="126" height="34" /> 
     <div align="center" style="margin-bottom: 10px; margin-left: 10px;"> 
      <button id="text" class="red" onclick="controls(this.getAttribute('class'),this.id)"></button> 

<img src="images/menuIcons/message.gif" width="126" height="34" /> 
    <div align="center" style="margin-bottom: 10px; margin-left: 10px;"> 
     <button id="message" class="red" onclick="controls(this.getAttribute('class'),this.id)"></button> 

<img src="images/menuIcons/game.gif" width="126" height="34" /> 
     <div align="center" style="margin-bottom: 10px; margin-left: 10px;"> 
      <button id="game" class="red" onclick="controls(this.getAttribute('class'),this.id)"></button> 

Javascript代碼:

// enable/disable Buttons 
function controls(className,elem) { 
    if (className == "red") { 
     document.getElementById(elem).setAttribute('class','green'); 
     // You can define your enable statements here 
    } else { 
     document.getElementById(elem).setAttribute('class','red'); 
     // You can define your disables statements here   
    } 
} 
+0

究竟是什麼問題?你只是想能夠點擊一個按鈕並將其變爲綠色,然後再次點擊將其變回紅色? – 2012-08-04 22:44:35

+0

@ChrisClower我相信他希望能夠點擊按鈕旁邊的文本來觸發按鈕。所以他有一個「按鈕」有兩個「開關」。 – Kiruse 2012-08-04 22:50:26

+0

我已將它設置爲當您單擊紅色圓圈時它變爲綠色,並且您再次單擊它時會回到紅色。這工作正常。我的問題是,如何在圖像左側製作圖像按鈕,當我點擊它們時,紅色按鈕變成綠色,而當我再次點擊按鈕時,圖像按鈕變回紅色。 – akamerc 2012-08-04 22:52:30

回答

1

你可以只調用從onclick功能在圖像上,太。不過,我建議重新構造controls函數,然後將id作爲參數。

<img src="images/menuIcons/skip.gif" onclick="controls('skip')" width="126" height="34" /> 
... 
<button id="skip" class="red" onclick="controls(this.id)"></button> 
<!-- the other elements analogous --> 
// enable/disable Buttons 
function controls(elemid) { 
    var elem = document.getElementById(elemid); 
    if (elem.className == "red") { 
     elem.setAttribute('class', 'green'); 
     // You can define your enable statements here 
    } else { 
     elem.setAttribute('class', 'red'); 
     // You can define your disables statements here   
    } 
} 
+0

你的救命謝謝 – akamerc 2012-08-04 23:16:28

0

這一切有點複雜。您可以用一個容器圍繞菜單,並使用event delegation爲所有項目添加點擊處理程序。這是一個(普通的javascript)jsfiddle mockup爲您的菜單。

在HTML /代碼的一些注意事項:

  • 不使用內聯樣式或JavaScript。內聯javascript在執行時產生一個新的解釋器 。
  • 在你的html中,你有不止一個 元素與id相同,這是要求麻煩。 id的應 是唯一的。
  • 也許你應該檢查jQuery,它可以節省你的工作。