2012-01-31 36 views
6

我知道我可以使用$ .data,但是如何迭代遍歷所有data-屬性並將這些值與默認插件配置合併?

(function($){ 

    $.fn.plugin = function(opts){ 

    opts = $.extend({ 
     foo: 'abc', 
     boo: 45 
    }, opts); 

    return this.each(function(){   
      ... 
    }); 

    }; 
})(jQuery); 

所以,如果我用

$('.el').plugin();

應該找數據屬性上.el,像數據富等..

回答

3

.data()方法支持數據 - 屬性。

從jQuery 1.4.3開始,HTML 5數據屬性會自動從 拉入到jQuery的數據對象中。在jQuery 1.6中修改了 嵌入破折號屬性的處理方式,以符合W3C HTML5 規範。

稱它沒有speciying參數將返回鍵/值對的對象爲所有的數據屬性:

var mydata = $("#mydiv").data(); 
2

您可以在jQuery對象上使用data()方法,這將給所有的數據屬性作爲鍵/值對。嘗試這個。

(function($){ 

    $.fn.plugin = function(opts){ 

    //this.data() will give { foo: 'abc', boo: 45 ... } 
    opts = $.extend(this.data(), opts); 

    return this.each(function(){   
      ... 
    }); 

    }; 
})(jQuery); 

.data()參考:http://api.jquery.com/data/

3

你可以得到這樣一個元素的所有屬性:

//get the element and setup an array for output 
var el = document.getElementById("o"), 
    arr = []; 

//loop through each attribute for the element 
for (var i = 0, attrs = el.attributes, l=attrs.length; i < l; i++){ 

    //if the current attribute starts with `data-` then add it to the array 
    if (attrs.item(i).nodeName.substr(0, 5) == 'data-') { 
     arr.push(attrs.item(i).nodeName); 
    } 
} 

這裏是一個演示:http://jsfiddle.net/ksbD3/1/

我也得到了大多數以上代碼從這個答案:Get all Attributes from a HTML element with Javascript/jQuery

5

在你each()循環,可以合併通過data()與您的默認值返回的對象,然後合併opts說法,結果在一個單一的呼叫$.extend()

$.fn.plugin = function(opts) { 
    return this.each(function() {   
     var thisOpts = $.extend({ 
      foo: "abc", 
      boo: 45 
     }, $(this).data(), opts); 
     // Now use 'thisOpts' as operating parameters for this element... 
    }); 
}; 

這應該達到你想要的一切:opts參數具有最高優先級,其次是當前元素的data-屬性,後面跟着插件默認值。

0

非常感謝所有使用opts = $ .extend(this.data(),opts)的答案;

這裏需要添加一個重要的事實:是HTML數據屬性的轉換。

數據爽Ñ AME可以這樣this.data(冷Ñ AME)

數據-另一人Ç ool- Ñ AME可以這樣這個被訪問來訪問。數據(另一個ç OOL ñ AME)

詳情:Does jQuery internally convert HTML5 data attribute keys to lowercase?

大小寫敏感的Java和屬性名的轉型可能是一個陷阱,如果你不知道的。