看了下jQuery手冊,自己做一個jQuery工具欄的插件。 (function($) { jQuery.fn.ToolBar=function(toolbar_id){ //找到或新增一個Toolbar對象bar,失敗時返回undefined //var bar=''; //var i,n,b; //i=0; //找到多於1個DOM對象,不適用,退出,返回空值 if (this.length>1)return; //this.Buttons=[] //生成新ID函數,根據指定類名稱name,然後自動生成的新ID this.NewToolId=function(name){ i=$('.'+name).length; //生成ID名稱 n=''+name+i; while ($('#'+n).length>0) { i+=1; n=''+name+i; } return n; }; //新增按鍵函數, this.AddButton=function(options){ //options={caption:顯示的標題,title:提示內容,click:點擊時響應的函數},沒有指定時使用默認內容進行創建 n=this.NewToolId('ToolButton'); defaults={caption:n,id:n,class:'ToolButton',type:'button'}; $.extend(defaults,options); cap=defaults.caption; click=defaults.click; delete defaults.click; delete defaults.caption; bs='<button '; $.each(defaults,function(n,v){ bs+=n+'="'+v+'" '; }); bs+='>'+cap+'</button>'; this.append(bs); b=$('#'+n); b.click=click if (click!=undefined){ b.bind('click',b.click); } this.Buttons.push(b); }; //添加ToolBar對象函數 this.AddToolBar=function(parent,options){ if(options==undefined || options.id==undefined ||$('#'+options.id).length==1){ n=this.NewToolId('ToolBar'); }else{ n=options.id; } if(options==undefined||otions.caption==undefined){ cap=n; }else{ cap=options.caption; } cs='<span class="ToolBarCaption">'+cap+'</span>'; if (parent==undefined){ parent=this;} parent.append('<div class="ToolBar" id="'+n+'">'+cs+'</div>'); b=$('#'+n); b.Caption=$('#'+n+'.ToolBarCaption'); //b.Bar=b[0] b.Buttons=[]; return b; }; //載入ToolBar DOM對象中的按鍵到Buttons中 this.LoadButtons=function(){ }; if (this.length==0) { //未找到DOM對象,Toolbar插入在body對象中。 //插入Toolbar div對象代碼 return this.AddToolBar($('body')); }else{ //找到一個DOM對象 if(this[0].className!='ToolBar'){ //對象不是ToolBar,使用它作為新ToolBar對象的父對象 return this.AddToolBar(); }else{ //指定ToolBar DOM對象,載入並生成jQuery對象 this.Caption=this.find('.ToolBarCaption'); if (this.Caption.length==0){ //指定的ToolBar中未包括ToolBarCaption,使用html作為ToolBarCaption n=this.html(); this.html(''); this.prepend('<span class="ToolBarCaption">'+n+'</span>'); this.Caption=this.find('.ToolBarCaption'); } this.Buttons=this.find('.ToolButton'); //this.Bar=this[0]; } } return this; }; })(jQuery); 下面幾行是使用例子。 function OnBtClick(event){ $('body').append('<p>'+event.target.id+'</p>'); } $(function() { tb=$.fn.ToolBar(); bt=tb.AddButton(); tb.AddButton(); tb=$.fn.ToolBar(); $('body').append('<p>end</p>'); tb1=$('#tb1').ToolBar(); tb1.AddButton({caption:'new'}); tb1.AddButton({caption:'save'}); $("a").click(function() { tb.AddButton({caption:'新增',title:'新增一條記錄',click:OnBtClick}); }); });