2014-02-07 84 views
3

我想向jQuery對象添加一個屬性,並將其附加到DOM,而不會污染DOM。在casu中,我想添加的屬性叫做'hue'。 (但是讓我們不要把這個屬性看作顏色向jQuery對象添加(讀寫)屬性

Ofcourse,有可能使用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元素。可能是因爲我沒有使用正確的關鍵字進行google搜索。

+0

din't測試你的代碼,但你不應該通過'hue_value'當你調用'this.setHue()'在'$ .fn.hue'功能?這樣的:'this.setHue(hue_value);' –

回答

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()); 
}); 
+0

的確如此。 – Ideogram

+0

讓我們來看看你的方法(這是行不通的)和我的(不起作用)之間的區別 >>(1)你使用jQuery的** data **函數。顯然,這對於內存泄漏和處理無法預料的情況也很重要。 (2)你的代碼利用jQuery的** each **方法來返回(鏈接)和設置propety。在我忽略的插件編寫中,這是一個很好的做法。 – Ideogram