重复使用 jquery 插件没有冲突

Reuse jquery plugin without conflict

我有一个用作进度条的小插件。问题是:我无法更新进度条的值,因为我所做的每项更改只会影响最后创建的对象 =(

另外..如果我称它为: $(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>

return 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>