$('input[type="radio"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked',false);
$radio.data('waschecked',false);
}
else
{
$radio.prop('checked',true);
$radio.data('waschecked',true);
}
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked',false);
});
最佳答案
我建议添加一个自定义属性来跟踪每个无线电的先前状态,如下所示:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked',false);
$radio.data('waschecked',false);
}
else
$radio.data('waschecked',true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked',false);
});
});
您还需要将此属性添加到最初检查的无线电标记中
JSFIDDLE DEMO
更新:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked',false);
$radio.data('waschecked',false);
}
else
$radio.data('waschecked',true);
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked',false);
});
});