【发布时间】:2017-01-03 18:20:56
【问题描述】:
我要做的是让用户单击一个表,该表在该表内选择一个单选按钮,然后将一个类添加到选定的表中。然后,如果用户在选中该收音机时选择了另一个表,则将添加该类,但也需要删除先前选择的表/收音机中的类。
现在大部分都有效,接受当我选择另一个收音机时,之前的课程不会被删除。仅当您切换收音机时,它才会被移除。
Here's a link to a demo on jsfidd在这里可以看到所有的html和其他JS。
$(function() {
$('table').click(function(event) {
if (event.target.type != "radio") {
var that = $(this).find('input:radio');
that.attr('checked', !that.is(':checked'));
if (that.is(':checked')) {
that.closest('table').addClass('selected');
}
else {
that.closest('table').removeClass('selected');
}
}
});
});
在我修改它之前我也忘记了我使用的是另一个版本。在这一个中,如果您实际单击单选按钮,样式将正确添加/删除,但在您单击表格时不会正确添加/删除。我试图将两者结合起来,这就是我获得上面发布的功能的方式..
This is the link to the jsfiddle with that demo,这也是我使用的 jquery。
// jQuery to select radio button within clicked table
$(function() {
$('table').click(function(event) {
if(event.target.type != "radio") {
var that = $(this).find('input:radio');
that.attr('checked', !that.is(':checked'));
}
});
});
// jQuery to change the style of the table containing the selected radio button
$(function() {
$('input[type="radio"]').change( function() {
// grab all the radio buttons with the same name as the one just changed
var this_radio_set = $('input[name="'+$(this).attr("name")+'"]');
for (var i=0; i < this_radio_set.length;i++) {
if ( $(this_radio_set[i]).is(':checked') )
$(this_radio_set[i]).closest('table').addClass('selected');
else
$(this_radio_set[i]).closest('table').removeClass('selected');
}
});
});
【问题讨论】:
标签: jquery radio-button removeclass checked