重用jquery插件没有冲突

时间:2015-06-08 18:09:42

标签: javascript jquery plugins makefile 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>

1 个答案:

答案 0 :(得分:0)

返回this.each...导致了问题 - 您正在为使用progBar方法创建的所有实例重新分配setValue函数。此更新应该让您朝着正确的方向前进:

&#13;
&#13;
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


});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<div id="elm1"></div>
<div id="elm2"></div>
&#13;
&#13;
&#13;