checkbox.js 1.7 KB
//Here is Checkbox.

/*
 * 依赖jquery
 * checkbox选中效果.
 * By 2014/09/11
 */
var checkbox = {
	target: {
		treeName: "cart-id", //treeName 为包裹input的最外层ID名
		element : "input.checkbox", //你要选中的子input
		fatherName: "infirst", //相对子input的全选父input
		extra: null
	},
	init: function(custom){
		this.target = $.extend(this.target,custom);

		var fit = $("."+this.target.fatherName);
		var tag = $("#"+this.target.treeName).find(this.target.element);

		this.checkState(tag);
		this.checkAll(fit,tag);
		this.checkout(fit,tag);
		if (typeof this.target.extra == "function"){
			this.target.extra();
		};
	},
	checkAll: function(fit,tag){
        this.checkbind(fit,function(){
			if (fit.attr("checked")=="checked"){
				tag.attr("checked","checked");
			}else {
				tag.removeAttr("checked");
			}
        });
	},
	checkout: function(fit,tag){
		var state = this.checkState(tag);

		this.checkCharge(state,fit);

        this.checkbind(tag,function(){
			state = checkbox.checkState(tag);
			checkbox.checkCharge(state,fit);
        });
	},
	checkState: function(tag){
		var cal=0;

		for (var i=0; i<tag.length; i++)
		{
			if (tag.eq(i).attr("checked")!="checked"){
				cal += 1;
			}
		}

		return cal;
	},
	checkCharge: function(state,fit){
		if (state>0){
			fit.removeAttr("checked");
		}else if (state==0){
			fit.attr("checked","checked");
		};
	},
    checkbind: function(obj,func){
		var bind=true;
		if (typeof func == "function"){ bind=false; }
		return bind || ( bind = obj.live("click",func) );
    },
	clear: function(tree){
		$("#"+tree).find( this.target.element.split(".")[0] ).removeAttr("checked");
	},
	start: function(custom){
		this.init(custom);
	}
};

checkbox.start();