Parse $ .extend configuration from data attribute

I know I can use $ .data, but how can I data- over all data- attributes and combine the values ​​with the default plugins configuration?

 (function($){ $.fn.plugin = function(opts){ opts = $.extend({ foo: 'abc', boo: 45 }, opts); return this.each(function(){ ... }); }; })(jQuery); 

So, if I use

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

it should look for data attributes on .el , for example data-foo, etc.

+6
source share
5 answers

Method . data () supports data attributes.

Like jQuery 1.4.3, the HTML data attributes will be automatically drawn into the jQuery data object. Attribute handling using inline dashes has been modified in jQuery 1.6 to meet the W3C HTML5 specification.

A call without specifying a parameter returns an object with key / value pairs for all data attributes:

 var mydata = $("#mydiv").data(); 
+3
source

In your each() loop, you can combine the object returned by data () with your default values, then merge the opts argument with the result into a single call to $. 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... }); }; 

This should provide what you want: the opts argument has the highest priority, followed by the data- attributes of the current element, and then the default values ​​for the plugin.

+5
source

You can get all the attributes for such an element:

 //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); } } 

Here is a demo: http://jsfiddle.net/ksbD3/1/

I also got most of the above code from this answer: Get all attributes from an HTML element using Javascript / jQuery

+3
source

You can use the data() method for a jQuery object that will give all data attributes as a key / value pair. Try it.

 (function($){ $.fn.plugin = function(opts){ //this.data() will give { foo: 'abc', boo: 45 ... } opts = $.extend(this.data(), opts); return this.each(function(){ ... }); }; })(jQuery); 

.data() link: http://api.jquery.com/data/

+2
source

Thanks for all the answers that indicate using opts = $ .extend (this.data (), opts);

One important fact to add here: this is the conversion of the HTML data attribute.

data-cool N ame can be obtained as this this.data (cool n ame)

data-another- c ool- n ame can be obtained as this this.data (another C ool N AME)

Details: Is jQuery internally converting HTML5 data attribute keys to lowercase?

The java case and attribute name conversion can be a trap if you don't know this.

0
source

Source: https://habr.com/ru/post/907345/


All Articles