【问题标题】:Toggle classes on divs when different radios are checked检查不同无线电时在 div 上切换类
【发布时间】:2014-06-11 22:57:46
【问题描述】:

坚持看似简单的任务,并尝试了一些变化,但没有成功。我有一张桌子,标签中有一些收音机。每个无线电都与同一列中的一组数据相关联。当我单击 中的收音机时,我想添加/删除一个类或切换类,以便在用户选择不同选项时突出显示每一列。

创建了我在这里尝试完成的示例小提琴:

JS FIDDLE

 <form id="myForm">
 <table>
<tr>
<th class="highlightMe option"> <input type="radio" name="radioName" value="1" checked="checked" class="option"/>one 
 </th>
 <th class="noClass option"><input type="radio" name="radioName" value="2" class="option"/>two 
 </th>
  <th class="noClass option"><input type="radio" name="radioName" value="3" class="option"/>three 
  </th>
  </tr>
  <tr>
   <td class="highlightMe">Highlight Me</td>
   <td class="noClass option">Or Highlight Me</td>
   <td class="noClass option">Or highlight three</td>
   </tr>
   </table>
   </form> 

一个带有背景的简单类,用于突出显示所有表格数据列:

.highlightMe {
background:#D32F32;
}

我尝试过的失败脚本之一:

  $('.option').each(function() {
var $this = $(this);
if($this.attr('checked')) {
    $this.addClass('highlightMe');
 } else {
    $this.removeClass('highlightMe');
 }
});

【问题讨论】:

    标签: jquery radio addclass checked toggleclass


    【解决方案1】:

    试试

    jQuery(function($) {
        $('.option').change(function() {
            var $this = $(this), $td = $this.parent(), $tr=$td.parent();
    
            $tr.next().add($tr).find('.highlightMe').removeClass('highlightMe');
    
            if(this.checked) {
                $tr.next().find('td').eq($td.index()).add($td).addClass('highlightMe')
            }
        });
    });
    

    演示:Fiddle

    【讨论】:

    • YAHTZEE!!!我什至没有接近。 (再次)感谢阿伦!将您的答案标记为正确。
    猜你喜欢
    • 2017-08-18
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    相关资源
    最近更新 更多