2012-08-04 98 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,它可以节省你的工作。