切换图像像单选按钮

时间:2014-10-06 07:15:25

标签: javascript jquery image radio-button toggle

我对jQuery和javascript有点新鲜。我有3张图像正在使用这些方法打开和关闭。

如何一次只能切换一个,类似于单选按钮。

<form class="num-players-group" action="">
  <input type="hidden" id='testbutton'>

  <a href="#" class="players2">
    <img src="Assets/Menu/DOR_players_2_off.png" style="display:inline-block" class="player-btn" alt="2 off" />
    <img src="Assets/Menu/DOR_players_2_on.png" style="display:none" class="player-btn" alt="2" />
  </a>

  <a href="#" class="players3">
    <img src="Assets/Menu/DOR_players_3_off.png" style="display:inline-block" class="player-btn" alt="3 off" />
    <img src="Assets/Menu/DOR_players_3_on.png" style="display:none" class="player-btn" alt="3" />
  </a>

  <a href="#" class="players4">
    <img src="Assets/Menu/DOR_players_4_off.png" style="display:inline-block" class="player-btn" alt="4 off" />
    <img src="Assets/Menu/DOR_players_4_on.png" style="display:none" class="player-btn" alt="4" />
  </a>

</form>

我也在使用jQuery:

$('.players2').click(function() {
  $(this).find('img').toggle();
});
$('.players3').click(function() {
  $(this).find('img').toggle();
});
$('.players4').click(function() {
  $(this).find('img').toggle();
});

我应该使用

的内容
$('.players4').not(this).removeClass('player-btn');

2 个答案:

答案 0 :(得分:0)

你可以使用这样的东西

JS Fiddle

$('.num-players-group a').click(function () {
    $(this).children('img').toggle();
});

答案 1 :(得分:0)

尝试使用:(注意:我已经简化了您的HTML类选择器):

&#13;
&#13;
$(function(){ // DOM ready
  
  var $plBtn = $('a.players');
  
  $plBtn.click(function(e){
    e.preventDefault();
    $plBtn.removeClass('selected'); // Remove selected class from all
    $(this).addClass('selected');   // Add to clicked Button
  });
  
});
&#13;
a.players{
  display:inline-block;
  text-decoration:none;
  border-radius:5px;
  overflow:hidden;
}
a.players img{
  vertical-align:middle;
}
a.players img+img{ display:none; } /* Hide next sibling image */

a.players.selected img    { display:none; }  /* if selected hide red image */
a.players.selected img+img{ display:block; } /* and show the green one     */
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="num-players-group" action="">
  <input type="hidden" id='testbutton'>

  <a href="#" class="players">
    <img src="//placehold.it/40x40/f00&text=2" alt="2 off" />
    <img src="//placehold.it/40x40/0ff&text=2" alt="2" />
  </a>

  <a href="#" class="players">
    <img src="//placehold.it/40x40/f00&text=3" alt="3 off" />
    <img src="//placehold.it/40x40/0ff&text=3" alt="3" />
  </a>

  <a href="#" class="players">
    <img src="//placehold.it/40x40/f00&text=4" alt="4 off" />
    <img src="//placehold.it/40x40/0ff&text=4" alt="4" />
  </a>

  </form>
&#13;
&#13;
&#13;

P.S:选择器+选择下一个兄弟元素。