2017-02-15 97 views
0

我有一个包含多行的HTML表格。在每一行中,第一列有一个问题(文本),第三,三个单选按钮分别在第2,3,4列中回答是,否或N/A。当在同一行上选择单选按钮时,更改表格单元格中的字体颜色

我希望能够改变文本的字体颜色在第一列进行检查或者在同一行中单选按钮的时候。

其他在这里#1问题是指改变,其中单选按钮所在的单元格的背景颜色,但在这种情况下,我需要修改第一列的属性在同一行来代替。

PS:你可以找到哑代码与this JSBin fiddle玩:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    <title>JS Bin</title> 
</head> 
<body> 
    <table border=1> 
    <tr> 
     <th>Question</th> 
     <th>Yes</th> 
     <th>No</th> 
     <th>N/A</th> 
    </tr> 
    <tr> 
     <td>Are you a student?</td> 
     <td><input type="radio" name="student"></td> 
     <td><input type="radio" name="student"></td> 
     <td><input type="radio" name="student"></td> 
    </tr> 
    </table> 
</body> 
</html> 

任何提示或建议会更受欢迎。提前致谢!

+0

你有jQuery的文档中加载? – Mojtaba

+0

@Mojtaba - 是的,我喜欢。不过,我忘了将它添加到JSBin小提琴中。 – gacanepa

回答

2

您可以设置事件侦听器。

您还可以获得所选择的值来设置基础上的价值,如果你想要的颜色。

$("input[name='student']").change(function(){ 
 
    console.log($(this).val()); 
 
    $(this).closest('tr').children('td').first().css('color', '#455434'); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<table border=1> 
 
    <tr> 
 
     <th>Question</th> 
 
     <th>Yes</th> 
 
     <th>No</th> 
 
     <th>N/A</th> 
 
    </tr> 
 
    <tr> 
 
     <td>Are you a student?</td> 
 
     <td><input value="1" type="radio" name="student"></td> 
 
     <td><input value="2" type="radio" name="student"></td> 
 
     <td><input value="3" type="radio" name="student"></td> 
 
    </tr> 
 
    </table>

+1

非常感谢!这就是我一直在寻找的! – gacanepa

+0

@ gacanepa,没问题。请记住,您可以删除'console.log'行。我只是添加它来告诉你如何获得选定的值 – Mojtaba

1
$(document).ready(function() { 
    $('input[type=radio][name=student]').change(function() { 
     $("td:first-child").css("color", "red"); 
    }); 
}); 

这可能会改变第一个td单元格的字体颜色时,单选按钮被选中的问题。

如果您想要,您可以添加条件语句以检查选中哪个复选框并更改字体颜色,因此当选择no时文本可以变为红色,选择yes时为绿色。

+0

非常感谢你!我希望我可以选择两个答案。 – gacanepa

1

您可以根据选择哪个无线上遍历DOM寻找点击该行的第一列,并改变颜色。

这里是一个Fiddle Demo

$('input:radio').on('click', function() { 
    //clear any existing background colors in the first column 
    $('table tr td:first-child').css('background','transparent'); 
    //find the index of the column that contains the clicked radio 
    var col = $(this).closest('td').index(); 
    //find the first td in that row 
    var firstTd = $(this).closest('tr').find('td:first-child'); 
    //set the color based on the column index of the clicked radio 
    var color; 
    switch (col) { 
    case 1: 
     color = 'red'; 
     break; 
    case 2: 
     color = 'green'; 
     break; 
    case 3: 
     color = 'purple'; 
     break; 
    } 
firstTd.css('background', color); 
}); 
+0

谢谢!这确实是一个很好的答案! – gacanepa

相关问题