jquery - 获取我的 jQuery 插件附加到的控件的 ID

标签 jquery jquery-plugins

我正在编写我的第一个 jQuery 插件。这是插件的框架:

(function( $ ) {
    var methods = {
        init : function( options ) { 
            var settings = $.extend( {
                'id' : '#' + this[0].id,
                'foo' : 3,       
                'bar' : 4,    
            }, options ); 
        }
   }

   $.fn.MyPlugin = function( method ) {
      if ( methods[method] ) {
        return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on MyPlugin' );
      }
  };
})( jQuery );

我像这样附加插件:

$( '#some-id' ).MyPlugin({
   'something' : 'something
});

对于一页上的一个控件来说效果很好,但是当我开始这样做时:

$( '#some-id-2' ).MyPlugin({
   'something' : 'something
});

$( '#some-id-3' ).MyPlugin({
   'something' : 'something
});

我收到以下错误:

Uncaught TypeError: Cannot read property 'id' of undefined

因为我从 this 获取我的 ID,对于不在我当前所在页面上的任何控件,其计算结果为 []!

获取插件所附加控件的 ID 的正确方法是什么?

非常感谢:)。

最佳答案

这里有一个基本问题:您正在考虑单个元素。 jQuery 就是关于元素。插件中的 this 是一个 jQuery 实例,其中可能有 0..n 匹配的元素。可能是零、一、27、342 等。因此,在 jQuery 插件中执行 this[0].id 并没有真正意义,因为您只会得到 第一个匹配元素的 id (如果它甚至有一个;没有要求它必须),或者当集合中根本没有任何元素时出现错误(正如您所发现的)。

因此,如果您开始将插件视为处理一组匹配元素(可能是空集、小集或大集),那么您就会陷入困境。正确的道路。

这是一个具体的例子:让我们编写一个插件来完成一件愚蠢的事情:它将元素变成一种颜色,然后在超时后将它们恢复为原始颜色。我们将像这样使用它:

$("selector").plugin("newcolor", timeout)

如果我们考虑单个元素,我们的插件将无法正常工作:

// The "foo" plug-in thinks in terms of just one element
$.fn.foo = function(color, time) {
    var self, oldColor;

    self = this;

    // Save the current color -- this is wrong
    oldColor = self.css("color");

    // Set new color
    self.css("color", color);

    // Restore old color after timeout
    setTimeout(function() {
      self.css("color", oldColor);
    }, time);
};

现在让我们使用它:

$("#theButton").click(function() {
    $(".foo").foo("blue", 1000);
});

...使用此 HTML:

<div class="foo">This is the first "foo" div</div>
<div class="foo" style="color: green">This is the second "foo" div</div>
<div class="foo" style="color: red">This is the third "foo" div</div>
<div><input type="button" id="theButton" value="Use foo"></div>

这里的问题是,通过考虑一个元素,插件错误地仅保存了第一个元素的颜色;当它“恢复”原始颜色时,它将第一个元素的颜色应用于所有其他元素,这是错误的。我们最终得到了三个使用黑色文本的 div,其中后两个不应该是黑色的。 Live example | Source

相反,如果我们从集合的角度思考,我们会这样做(例如;并不是说这是地球上最漂亮的代码):

// The "bar" plug-in understands sets
$.fn.bar = function(color, time) {
    var self;

    self = this;

    // Get the current color of each element
    self.each(function() {
      var entry = $(this);
      entry.data("oldColor", entry.css("color"));
    });

    // Set new color
    self.css("color", color);

    // Restore old color after timeout
    setTimeout(function() {
      self.each(function() {
        var entry = $(this);
        entry.css("color", entry.data("oldColor")).removeData("oldColor");
      });
    }, time);
};

我们将像这样使用它(基本相同):

$("#theButton").click(function() {
    $(".bar").bar("blue", 1000);
});

...使用此 HTML(基本相同):

<div class="bar">This is the first "bar" div</div>
<div class="bar" style="color: green">This is the second "bar" div</div>
<div class="bar" style="color: red">This is the third "bar" div</div>
<div><input type="button" id="theButton" value="Use foo"></div>

请注意它如何保存每个元素的颜色,以及如何通过数据保存元素本身。恢复时,它恢复每个元素的颜色。 Live example | Source

关于jquery - 获取我的 jQuery 插件附加到的控件的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9311633/

相关文章:

javascript - 如何使用 javascript 启用和禁用图像加载

jquery - 从 jQuery 插件中调用函数

jquery - 分发 jQuery 插件 - 需要哪些文件?

c# - 如何将 jqGrid 与 C#/ASP.NET 和 JSON.NET(没有 AJAX.NET 的东西)一起使用?

javascript - jQuery - 类型错误 : callback is undefined

Javascript 命名空间冲突

javascript - 响应式 Youtube 视频 - 折叠

javascript - .on 更改 vs .on click

c# - 使用 Jquery 禁用 ASPX 页面上的后台或所有控件

javascript - 解析 "Streaming"JSON