簡體   English   中英

重復使用jQuery插件而不會發生沖突

[英]Reuse jquery plugin without conflict

我有一個小插件作為進度欄。 問題是:我無法更新progressbar的值,因為我所做的每一次更改都會影響最后創建的對象=(

也..如果我這樣稱呼它:$(node-selector).progBar()。setValue()它可以調用正確的節點,但是會丟失配置對象

遵循代碼:

  var elm1; var elm2; $(function($){ $.fn.progBar = function ( config ){ if ( typeof ( config ) === "string" ) { config = {'text':config} ; } var config = $.extend ({ 'text' : false }, config ); return this.each(function( ){ var $this = $(this); // $this is the main element $this.css("width","200px") $this.css("padding","4px 10px") $this.css("text-align","center") $this.css("background","#eee") $this.css("font-weight","bold") $this.css("border","1px solid #00F") $this.html(config.text) $.fn.setValue = function ( newValue ) { $this.html(config.text + " " + newValue) }; }); }; elm1 = new $("#elm1").progBar("this is the first...") elm2 = new $("#elm2").progBar("this is the seccond...") // both lines below just affect the #elm2 object elm1.setValue("first") elm2.setValue("seccond") // this will overrite line above }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id="elm1" ></div> <div id="elm2" ></div> 

返回this.each...導致了問題-您正在為使用progBar方法創建的所有實例重新分配setValue函數。 此更新應該使您朝正確的方向前進:

 var elm1; var elm2; $(function($) { $.fn.progBar = function(config) { if (typeof(config) === "string") { config = { 'text': config }; } var config = $.extend({ 'text': false }, config); this.css("width", "200px") this.css("padding", "4px 10px") this.css("text-align", "center") this.css("background", "#eee") this.css("font-weight", "bold") this.css("border", "1px solid #00F") this.html(config.text) this.setValue = function(newValue) { var currentInnerText = this.html(); this.html(currentInnerText + " " + newValue) }; return this; }; elm1 = new $("#elm1").progBar("this is the first..."); elm2 = new $("#elm2").progBar("this is the seccond..."); // both lines below just affect the #elm2 object elm1.setValue("first"); elm2.setValue("seccond"); // this will overrite line above }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id="elm1"></div> <div id="elm2"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM