我需要运行一个函数,使复选框的行为类似于单选按钮.我知道,长话故事.无论如何,我想让它更易于重复使用,而不必为每个组重写它.我有这样的工作:
$(function() {
var $apples = $('input.apples');
$apples.click(function() {
$apples.removeAttr('checked');
$(this).attr('checked', true);
});
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能使这个更加全局化,以便如果我有另一组复选框.bannanas它也适用于它们而不必重写它?
谢谢
制作一个插件:
示例: http ://jsfiddle.net/YbGtE/2/
(function($) {
$.fn.makeRadios = function() {
var $items = this;
return this.click(function() {
$items.removeAttr('checked');
$(this).attr('checked', true);
});
};
})( jQuery );
$('input.apples').makeRadios();
$('input.bananas').makeRadios();
Run Code Online (Sandbox Code Playgroud)
编辑:根据下面的评论中的要求,要取消选中双击复选框,请执行以下操作:
示例: http ://jsfiddle.net/YbGtE/3/
(function($) {
$.fn.makeRadios = function() {
var $items = this;
return this.click(function() {
$items.removeAttr('checked');
$(this).attr('checked', true);
}).dblclick(function() {
$items.removeAttr('checked');
});
};
})( jQuery );
$('input.apples').makeRadios();
$('input.bananas').makeRadios();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |