单击单选按钮,将类添加到父级

时间:2015-02-05 15:43:37

标签: jquery

我有以下代码,当你单击一个单选按钮时,它会添加类checked_radio,当你点击另一个单选按钮时,它会删除该类,然后将该类添加到另一个单选按钮。这很有效。

第二部分是我想要做类似的事情但是将类highlighted添加到父li,它添加它很好但是在单击另一个单选按钮时不删除该类。我做错了什么?

$('.gfield_radio input').click(function() {
   $('.gfield_radio input').removeClass("checked_radio");
   $(this).addClass("checked_radio");

   $('input.checked_radio').closest('li').removeClass("highlighted");
   $(this).closest('li').addClass('highlighted');   
});

3 个答案:

答案 0 :(得分:4)

使用这些行,您可以确保之前的任何.gfield input不再具有checked_radio,然后将其添加到刚刚点击的那个:

$('.gfield_radio input').removeClass("checked_radio");
$(this).addClass("checked_radio");

然后,在这之后,你使用它来尝试删除旧的亮点:

$('input.checked_radio').closest('li').removeClass("highlighted");

当然,到那时,您已经更新了哪个单选按钮具有checked_radio类。

只需改变顺序:

$('.gfield_radio input').click(function() {
   // Out with the old...
   $('input.checked_radio').closest('li').removeClass("highlighted");
   $('.gfield_radio input').removeClass("checked_radio");

   // ...and in with the new
   $(this).addClass("checked_radio")
          .closest('li').addClass('highlighted');   
});

答案 1 :(得分:0)

最好的办法就像@ T.J.Crowder给你的那样。

您也可以使用:

$('.gfield_radio input').click(function() {
   $('.gfield_radio input').removeClass("checked_radio");
   $(this).addClass("checked_radio");

   //or may be $('.gfield_radio li').removeClass('highlighted');
   $('.gfield_radio input').closest('li').removeClass("highlighted");
   $(this).closest('li').addClass('highlighted');   
});

答案 2 :(得分:0)

我会这样做:

// Cache your selectors so you're not always calling the jQuery method
var $radios = $('.gfield_radio input'),
    $listItems = $('.gfield_radio li');

// Listen to the `change` event instead of `click`, to ensure that it
// only happens when the user has explicitly changed the radio's value
$radios.on('change', function(e) {
  var $this = $(this),
      // Ensure you grab the correct `li` by using `parents()`
      $parent = $this.parents('li');

  // Now you can remove/add classes as you need without having to call
  // `jQuery()` again and again.
  $radios.removeClass('checked_radio');
  $listItems.removeClass('highlighted');
  $this.addClass('checked_radio');
  $parent.addClass('highlighted');

});

与其他答案类似,但清理了一下。希望这会有所帮助。