我正在寻找允许我取消选择单选按钮的脚本。我在SO上找到了一个并在这里实现了......
http://jsfiddle.net/sparky672/YFsVK/1/
正如您所看到的那样,只有当您单击单选按钮本身时,它才能正常工作。 (您也可以通过点击相应的<label>
文字来“选择”按钮。默认情况下,这是<label>
的操作方式。)
但是,我还需要能够通过单击相应的<label>
来“取消选择”单选按钮,这是我需要帮助的地方。
(为什么?因为我使用的插件使用<label>
中包含的图像精灵以图形方式改变了单选按钮的外观,覆盖了默认的单选按钮。我的jsFf中有一条线你可以激活以查看插件的运行情况。)
我确定我只需要稍微调整一下这个脚本,但我似乎无法弄清楚它。我相信我只需要在操作相应的单选按钮时“选择”<label>
。通过将<label>
按钮放在相应id
的{{1}}属性中,for
会“附加”到按钮上。
JavaScript的:
<label>
HTML:
$(document).ready(function() {
$('input[name="amount"]').mousedown(function(e) { // allows radio button deselection
var $self = $(this);
if ($self.is(':checked')) {
var uncheck = function() {
setTimeout(function() {
$self.removeAttr('checked');
}, 0);
};
var unbind = function() {
$self.unbind('mouseup', up);
};
var up = function() {
uncheck();
unbind();
};
$self.bind('mouseup', up);
$self.one('mouseout', unbind);
}
});
});
答案 0 :(得分:3)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".radio-label").click(function(e) {
var radio = $(this).attr("for");
radio = $("#" +radio );
if(radio.is(":checked")) {
e.preventDefault();
radio.removeAttr("checked");
}
});
});
</script>
</head>
<body>
<fieldset id="radioset">
<input type="radio" id="radio-1" name="amount" value="Option 1" /><label class="radio-label" for="radio-1" title="">Option 1</label><br />
<input type="radio" id="radio-2" name="amount" value="Option 2" /><label class="radio-label" for="radio-2" title="">Option 2</label><br />
<input type="radio" id="radio-3" name="amount" value="Option 3" /><label class="radio-label" for="radio-3" title="">Option 3</label><br />
<input type="radio" id="radio-4" name="amount" value="Option 4" /><label class="radio-label" for="radio-4" title="">Option 4</label><br />
<input type="radio" id="radio-5" name="amount" value="Option 5" /><label class="radio-label" for="radio-5" title="">Option 5</label>
</fieldset>
</body>
</html>
答案 1 :(得分:2)
我也尝试过@Jrod做了什么,并注意到插件不起作用。所以我修改了插件。基本上将其添加到标签:
.bind('mouseup', function(){
if ($(this).is('.checked') && input.is(':radio')) {
setTimeout(function(){
label.removeClass('checked focus');
input.removeAttr('checked').blur();
}, 0);
}
});
这是updated demo。