jsfiddle
http://jsfiddle.net/cCBUh/2/
信息
问题
当第二次单击单选按钮时,不要从所有单选按钮中移除选中的按钮。为什么会这样呢?解决办法?
<div class="panel">
<label for="radio-1">Radio 1</label>
<label for="radio-2">Radio 2</label>
<label for="radio-3">Radio 3</label>
<input type="radio" id="radio-1" name="group-1">
<input type="radio" id="radio-2" name="group-1">
<input type="radio" id="radio-3" name="group-1">
</div>jQuery
jQuery(document).ready(function($) {
$('.panel label').on( "click", function(e) {
console.log('clicked');
var my_id = $(this).attr('for');
if( $('.panel #' + my_id).is(':checked') ) {
console.log('checked');
$('.panel input[type="radio"]').prop('checked', false);
}
});
});发布于 2013-09-20 08:23:23
我认为问题在于,带有id属性的标签上的默认单击行为强制这样做。我更改了您的javascript以执行您想做的事情,并添加了更多的调试:
http://jsfiddle.net/cCBUh/15/
jQuery(document).ready(function($) {
$('.panel label').on( "click", function(e) {
// prevent the html to automatically check the corresponding checkbox
e.preventDefault();
var my_id = $(this).attr('for');
console.log('clicked: ' + my_id);
if( $('#' + my_id).is(':checked') ) {
console.log('checked: ' + my_id);
$('#' + my_id).prop('checked', false);
} else {
console.log('check now: ' + my_id);
$('#' + my_id).prop('checked', true);
}
});
});但是,您也可能希望将这种行为应用到单选按钮本身的onClick上?
https://stackoverflow.com/questions/18911649
复制相似问题