checkbox.js
2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Checkbox组件
* 使用:
* 1. 多选多或一选一 $(selector).checkbox()
* 2. 多选一 需要为父元素添加'multi-checkbox'的class $(selector).checkbox()
* 3. 为checkbox添加data-checkbox='false', 该checkbox将不会初始化为Checkbox组件
*/
define('checkbox', ['components/common', 'jquery'], function() {
var labelTmp = "<label class='checkbox-inner'></label>";
var defaultSettings = {
onClick: function () { }
};
var Checkbox = function(ele, settings) {
var $checkbox = $(ele),
id = ele.id;
settings = $.extend({}, defaultSettings, settings);
if($checkbox.next(".checkbox-inner").length) return; // 防止重复调用
if($checkbox.attr("data-checkbox") == 'false') return; // 防止与其他同类型组件冲突
if(!id) {
id = 'checkbox'+Checkbox.index++;
$checkbox.attr('id', id);
}
$checkbox.addClass("checkbox");
$checkbox[0]._onclick = settings.onClick;
$checkbox.parent().addClass("checkbox-wrapper");
$(labelTmp).insertAfter($checkbox).attr("for", id);
};
Checkbox.index = 0;
$("body").on("click.singleCheckbox", ".multi-checkbox .checkbox-inner", function() {
var $checkbox = $(this),
$checkboxWrapper = $checkbox.parents(".multi-checkbox");
$checkboxWrapper.find(".checkbox").each(function() {
$(this).prop("checked", false);
});
$checkbox = $checkbox.siblings(".checkbox").trigger("click");
setTimeout(function() {
$checkbox.prop("checked", true);
$checkbox[0]._onclick();
});
}).on("click.oneCheckbox", ":not(.multi-checkbox)>.checkbox-wrapper .checkbox-inner", function(){
var $checkbox = $(this).siblings(".checkbox");
setTimeout(function () {
$checkbox[0]._onclick();
});
});
$.fn.checkbox = function(settings) {
var $el = $(this);
if($el.attr("type") == "checkbox") {
new Checkbox(this, settings);
} else {
$el.find("input[type=checkbox]").each(function() {
new Checkbox(this, settings);
});
}
return $el;
};
$.fn.checked = function(unchecked) {
var $el = $(this);
setTimeout(function() {
if (unchecked) return $el.removeProp("checked");
$el.prop("checked", "checked").triggerHandler("click");
}, 50);
};
});