对两个按钮使用toggleClass – 使用$(this)jquery对象发出问题

当鼠标在其中一个上面时,我想制作2个按钮的翻转颜色。 我有以下HTML:

和CSS:

 .btn-classic { color: black; background-color: white; } .btn-inverse { color: white; background-color: black; } 

首先,我专注于第一个按钮组,其div容器是id="PlayerVsComputer" 。 我尝试通过以下方式选择.btn class的两个按钮:

 var playerVsComputerContainer = $('#PlayerVsComputer .btn'); 

鼠标hover在2个按钮之一上时创建以下function:

 playerVsComputerContainer.hover(function() { $(this).toggleClass('btn-inverse'); $(this).toggleClass('btn-classic'); }); 

我意识到playerVsComputerContainer可能是一个jQuery对象的数组( 想要确认 ),因为在Javascript控制台上,我得到:

 >> $('#PlayerVsComputer button.btn'); Object { 0: button.btn.btn-inverse.btn-xs, 1: button.btn.btn-classic.btn-xs, length: 2, ... 

从这开始,我尝试只选择一个按钮:

 playerVsComputerContainer.hover(function() { $(this)[0].toggleClass('btn-inverse'); $(this)[0].toggleClass('btn-classic'); }); 

但似乎$(this)[0]无效。 我做了上游:

 playerVsComputerContainer[0].hover(function() { $(this).toggleClass('btn-inverse'); $(this).toggleClass('btn-classic'); }); 

不幸的是,这不起作用。 我只是希望当鼠标hover在它上面时,2个左右侧按钮的颜色会翻转它们的初始颜色(黑色和白色)(之后,我希望用户通过鼠标点击确认当前颜色的这种变化)。

你可以在这个jsfiddle上看到测试

 var playerVsComputerContainer = $('#PlayerVsComputer .btn'); playerVsComputerContainer.mouseover(function() { $(this).toggleClass('btn-inverse'); $(this).toggleClass('btn-classic'); //$(this)[0].toggleClass('btn-inverse'); //$(this)[0].toggleClass('btn-classic'); }); 
 .btn-classic { color: black; background-color: white; } .btn-inverse { color: white; background-color: black; } 
  

更新1:我必须确切地说,当鼠标超出2个左右侧按钮时,我希望原始颜色再次出现:我必须使用hover还是mouseover

由于相同的函数可以作为handlerIn和handlerOut运行,因此不需要将与第二个参数相同的函数传递给.hover方法。 请参阅jQuery .hover规范。

检查此代码段。 可能这是你正在寻找的行为。
当鼠标hover在按钮上时,它会切换。
当鼠标移出按钮时,它会切换回原始样式。

在你的html中,类名拼写错误为btn-clssic

您的代码所需的更正是

  playerVsComputerContainer.hover(function() { $(this).toggleClass('btn-inverse'); $(this).toggleClass('btn-classic'); }); 

这可以简化如下。

 playerVsComputerContainer.hover(function() { $(this).toggleClass('btn-inverse btn-classic'); }); 

请参阅jQuery toggleClass规范。

 $('#PlayerVsComputer .btn').hover(toggle); function toggle() { $(this).toggleClass('btn-inverse btn-classic'); } 
 .btn-classic { color: black; background-color: white; } .btn-inverse { color: white; background-color: black; } 
  

如果我理解正确,我需要在hover在按钮上时更改按钮的颜色。 此代码使用2个函数。 当您将鼠标hover在具有.btn类的任何按钮上时执行一个,当您从按钮中移除焦点时执行另一个按钮。

 $('.btn').hover( function() { $(this).addClass('btn-classic'); }, function() { $(this).removeClass('btn-classic'); } ); 
 .btn-inverse { color: white; background-color: black; } .btn-classic { color: black; background-color: white; }