【问题标题】:Add (read and write) a property to the jQuery object向 jQuery 对象添加(读取和写入)属性
【发布时间】:2014-02-07 08:56:21
【问题描述】:

我想为 jQuery 对象添加一个属性,从而将其附加到 DOM 而不污染 DOM。在这种情况下,我想添加的属性称为“色调”。 (但我们不要将此属性视为 color

当然,也可以使用 jQuery 的“数据”功能,而且效果很好。但是,它使我的代码可读性降低。

$("#a").data("hue","123");
$("#b").data( $("#a").data("hue")  );

我还设法创建了一个 getter 和 setter 函数,它的可读性已经大大提高了。

$("#a").setHue(123);
$("#b").setHue(  $("#a").getHue()   ); 

最终,我想要实现的是能够像这样编写我的 jQuery/javascript 代码:

$("#a").hue(123);
$("#b").hue(  $("#a").hue()   ); 

但是,它不起作用,并且在 firebug 中评估它时,我的浏览器崩溃了。

这是我目前创建的代码。 getHue() 和 setHue('123') 有效,Hue() 无效。

//extend the jQuery object with some extra properties for sake of readability
(function($)
{
    $.fn.setHue = function(hue_value)
    {
        this.hue=hue_value;
        return this;
    };

    $.fn.getHue = function()
    {
        return this.hue;
    };

    $.fn.hue = function(hue_value)
    {
        if ( typeof hue_value === 'undefined' ){
            return this.getHue();
        } else {
            this.setHue();
            return this;
        }
    };


})(jQuery);

我尝试研究谷歌搜索、阅读论文书籍并阅读有关插件创建的 jQuery API。但是,这些都专注于创建更多功能的插件,操作 DOM 元素。可能是我没有用谷歌搜索正确的关键字。

【问题讨论】:

  • 不要测试你的代码,但是当你在你的$.fn.hue 函数中调用this.setHue() 时,你不应该传递hue_value 吗?这样:this.setHue(hue_value);

标签: jquery jquery-plugins code-readability


【解决方案1】:

喜欢这样吗? http://jsbin.com/doxa/1/edit

(function($){

  $.fn.hue = function (value) {
    if(value) {
      return this.each(function() {
        $(this).data('hue', value);
      });
    }
    return this.data('hue');
  };

})(jQuery);

$(function () {
  $('#a').hue('xxx');
  $('#b').text($('#a').hue());
});

【讨论】:

  • 让我们注意您的方法(有效)和我的方法(无效)之间的差异 >> (1) 您使用了 jQuery 的 data 函数。显然,这对于内存泄漏和处理不可预见的情况也很重要。 >> (2) 您的代码使用 jQuery 的 each 方法来返回(链接)和设置属性。这是我忽略的插件编写的一个好习惯。
猜你喜欢
  • 1970-01-01
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多