我正在尝试将类添加到选定的无线电输入中,然后选择同一类型的另一个无线电时删除该类

单选按钮的类为“radio_button”,但我无法获得 要使用以下代码更改的类。

  jQuery(".radio_button").livequery('click',function() {  

      $('input.radio_button :radio').focus(updateSelectedStyle);
      $('input.radio_button :radio').blur(updateSelectedStyle);
      $('input.radio_button :radio').change(updateSelectedStyle);
  }
  function updateSelectedStyle() {
      $('input.radio_button :radio').removeClass('focused');
      $('input.radio_button :radio:checked').addClass('focused');
  }
有帮助吗?

解决方案

Tre问题是由选择器中的一个额外空间引起的。

而不是:

$('input.radio_button :radio')

你想写:

$('input.radio_button:radio')

其他提示

您可能还希望利用jQuery的可链接性来减少您正在进行的工作量。 (而不是一遍又一遍地重新找到这些按钮。)像这样:

  jQuery(".radio_button").livequery('click',function() {  
    $('input.radio_button:radio')
      .focus(updateSelectedStyle)
      .blur(updateSelectedStyle)
      .change(updateSelectedStyle);
  });
  function updateSelectedStyle() {
    $('input.radio_button:radio')
      .removeClass('focused')
      .filter(':checked').addClass('focused');
  }
  • 为每个单选按钮指定一个唯一的 ID
  • 点击传递ID
  • 删除具有相同类的所有单选按钮的“focussed”类名称
  • 使用您传递的 ID 将“focussed”类添加到单选按钮

首先,我同意Rene Saarsoo关于额外空间的回答。

其次,您是否也尝试将样式应用于单选按钮标签?您可能希望以某种方式将按钮和标签包装在一起。例如:

<span class="radiowrapper"><input type="radio" name="system" value="1" class="radio_button"> 1</span>
<br>
<span class="radiowrapper"><input type="radio" name="system" value="2" class="radio_button"> 2</span>

然后在你的livequery调用中删除额外的调用,并将代码从 updateSelectedStyle()函数移动到你的livequery调用中(我注意到了IE的问题):

   jQuery(".radio_button").livequery('click',function() {
        $('input.radio_button:radio').parent(".radiowrapper").removeClass('focused');
        $('input.radio_button:radio:checked').parent(".radiowrapper").addClass('focused');
   });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top