simulate.js
1.98 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
/*
* Simulate the input["checbox" || "radio"];
* Recode in 2015/07/16
* By van
*/
define( 'simulate' ,function( require, exports, module ){
var simulate = function(target, options){
var opt = $.extend({
'target': 'input',
'tpl': {
'chk': '<i class="ic s-chk"></i>',
'rdo': '<i class="ic s-rdo"></i>'
},
'open': 'Simuopen'
}, options);
//Cache some long varialbe name.
var tpl = opt.tpl, op = opt.open;
var doms = {};
//Pack every node in target.
_each(target, function(tag){
_pkgroom(tag);
});
//As the input.name different, the clickTarget is defferent.
_each(doms, function(dom_each){
_each(dom_each, function(de, des){
//Bound ClickEvent For change the checked display.
$(de).on({
click: function(){
_this = this;
_each(des, function(_d){
_d != _this || !_this.checked ? $(_d).parent().removeClass(op) : $(_this).parent().addClass(op);
});
}
})
})
}, 'O');
/*
* Loop a unit which is [array] or {object}
* And run a callback to do something.
* @parem {Array/Object, function, string}
* @return {Array/Object}
*/
function _each(arr, fn, type){
switch(type){
case 'O':
for (var each in arr){
fn(arr[each], arr);
};
break;
default:
for (var i = 0, l = arr.length; i < l; i++){
fn(arr[i], arr);
};
};
return arr;
};
/*
* Distinguish the input and pack different html package.
* Only two type ['radio', 'checkbox'].
* @param {HTMLDOM}
* @return
*/
function _pkgroom(target){
var inp = $(target).find(opt.target)[0];
inp && inp.type == 'radio' ? $(inp).after(tpl.rdo) : $(inp).after(tpl.chk);
var name = inp.name;
doms[name] != null ? doms[name].push(inp) : doms[name] = [inp];
};
};
return simulate;
});