一个很简单的动态改变class插件

;(function($) {

/**
*	初始化插件
*	@author: luofei
*	@version: 2013/03/22
*	@param:	{array}		options		初始化传入的json数据
*/

$.fn.lf = function(options){
	this.opts = $.extend({}, $.fn.lf.defaults, options);
	this._init();
};

/*
*	插件的扩展函数	公共方法
 */
$.fn.lf.prototype = {
	_init: function() {

		var _this = this;	//获取当前对象
		
		//根据传入的参数确定选择器
		var selector = _this.opts.id === "" ? "."+_this.opts.className : "#"+_this.opts.id;

		$(selector).each(function(index) {
			$(this).bind(_this.opts.eventType,makeFunc(index,_this.opts));
		});
	}
}

/*
*	内部私有方法	--闭包	
*	@param:	{int}	index	当前遍历的对象数组下标
*	@param:	{array}		opts	插件配置选项
* */
function makeFunc(index,opts){
	return function(){
		if(opts.id)
			var item = $("#"+opts.id);
		var item = $("."+opts.className);
		for(var i=0; i<item.length; i++){
			var attr = item[i].getAttribute("class");
			if(i != index){
				attr = attr.replace(opts.toggleName,"");
				item[i].setAttribute("class",attr);
			}
			else{
				item[i].setAttribute("class",attr+" "+opts.toggleName);
			}
		}
	};
}

/*
	* @param	{string}	id			选择器 id
	* @param	{string}	className	选择器 class
	* @param	{string}	toggleName	需增加的class
	* @param	{string}	eventType	事件触发的类型
*/
$.fn.lf.defaults = {
	id: "",
	className: "",
	toggleName: "",
	eventType: "click"
};

})(jQuery);

//应用实例
$(function(){
	var lf = new $.fn.lf({
		className: "item",
		toggleName: "active"
	});
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值