如何:如果数据属性等于 radio select 添加 class

How to: If data attribute equals radio select add class

我在弄清楚如何对此进行编码时遇到了问题,我是 JS/jQuery 的新手,所以请放轻松!

我想获取选中的单选按钮的id,我已经完成了。然后我想找到具有匹配数据属性的 table 行 <tr> 并向其添加 class。我的问题是试图找到数据属性的值导致 TR 返回未定义,因为有多个数据属性,所以我不能这样做:

if (dataAttribute = radioSelect) {
    $(this).addClass("test");
}

基本上我的问题是多个 table 行并且不知道如何将它们挑出来。

这是我的代码的粗略示例:

https://jsfiddle.net/2dsvrhjo/1/

非常感谢任何帮助。

这里有一个简单的例子:

$('input[type="radio"]').on('change',function () {
        // Get Choice for Application
    var application = $(this).attr('id');
  $('table').find('tr').each(function(i){
      if ($(this).attr('data-app') == application){
        $(this).addClass('test');
      } else {
        $(this).removeClass('test');
      }

  });
});

只需使用上面的代码更新您的 fiddle。

该代码正在遍历每个代码并检查是否匹配 'data-app'

您可以通过 data-attributes select 像这样:

$('input[type="radio"]').change(function () {
    // Get Choice for Application
    var application = $('input[name="application"]:checked').prop('id') || '';
  
    // Get all tr's with the selected data-app
    var $trs = $('tr[data-app="'+application+'"]');
  
    // Add your class
    $trs.addClass('highlight');
  
    // Remove the class from all other tr's
    $('tr').not($trs).removeClass('highlight');
});
.highlight {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="radio" id="Aviation" name="application" />Aviation<br>
  <input type="radio" id="Civil" name="application" />Civil
</div>
<table border="1" style="text-align:center;">
  <tr>
    <th>Section One</th>
    <th>Section Two</th>
  </tr>
   <tr data-app="Aviation">
    <td>Lorem Ipsum</td>
    <td>Lorem Ipsum</td>
  </tr>
  <tr data-app="Civil">
    <td>Lorem Ipsum</td>
    <td>Lorem Ipsum</td>
  </tr>
  <tr data-app="Aviation">
    <td>Lorem Ipsum</td>
    <td>Lorem Ipsum</td>
  </tr>
  <tr data-app="Civil">
    <td>Lorem Ipsum</td>
    <td>Lorem Ipsum</td>
  </tr>
</table>