问题
Got a small problem with some very basic jQuery, I'd like to be able to click on a table cell, and then have it automatically select the radio button inside.
HTML:
<table>
<tr>
<td>
1<br>
<input type="radio" name="choice" value="1">
</td>
<td>
2<br>
<input type="radio" name="choice" value="2">
</td>
<td>
3<br>
<input type="radio" name="choice" value="3">
</td>
</tr>
</table>
jQuery:
$("td").click(function () {
$(this).closest('input:radio').attr('checked',true);
});
Any help would really be appreciated, thank you!
回答1:
Use this selector:
$('input:radio', this).attr('checked', true);
Or using find
method:
$(this).find('input:radio').attr('checked', true);
Here is how your code should look like:
$("td").click(function () {
$(this).find('input:radio').attr('checked', true);
});
回答2:
Try
$(this).find('input:radio').attr('checked','checked');
回答3:
Try find instead of closest.
$(this).find('input:radio').attr('checked',true);
回答4:
This works perfectly
$(function () {
$('td').click(function () {
var cell = $(this),
state = cell.data('state') || 'first';
switch (state) {
case 'first':
cell.data('state', 'second');
cell.find('input:radio').attr('checked', true);
cell.find('input:radio').data('checked', true);
cell.find('input:radio').prop('checked', true);
break;
case 'second':
cell.data('state', 'first');
cell.find('input:radio').attr('checked', false);
cell.find('input:radio').data('checked', false);
cell.find('input:radio').prop('checked', false);
break;
default:
break;
}
});
});
来源:https://stackoverflow.com/questions/4625037/click-td-select-radio-button-in-jquery