像单选按钮一样切换图像

Toggling images like radio buttons

本文关键字:一样 图像 单选按钮      更新时间:2023-09-26

我对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');

您可以使用类似的东西

JS Fiddle

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

试一下:(注意:我简化了您的HTML类选择器):

$(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
  });
  
});
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     */
<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>

p.S:选择器+选择下一个同级元素。