【问题标题】:Reuse jquery plugin without conflict重用jquery插件不冲突
【发布时间】:2015-08-23 07:59:33
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery plugins makefile conflict


    【解决方案1】:

    返回 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>

    【讨论】:

    • 很高兴听到这个消息。如果这回答了您的问题,请单击答案左侧的复选标记以接受它。谢谢!
    猜你喜欢
    • 2012-08-20
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多