Home > Net >  How to properly author or create a JQuery plugin that supports HTML data-*attributes?
How to properly author or create a JQuery plugin that supports HTML data-*attributes?

Time:11-24

I am currently creating a JQuery Plugin that support data-attributes for defining options. I scoured the internet for sources on how to propery do it, but cannot find any.

What I have done so far:

HTML:

 <table id="myTable" data-columns='[{ "header": "Header1" },
                { "header": "Header2" },
                { "header": "Header3" }]'>
    </table>

Plugin:

 $.fn.myPlugin = function () {
        columns:""

    }
    var self = $(this)
    var foo = self.data("columns")

    //..some code to create columns

Plugin Usage:

$("#myTable").myPlugin()

CodePudding user response:

Here is a minimal jQuery plugin based on your question.

(function( $ ) {
    $.fn.myPlugin = function () {
        this.filter('table').each(function() {
            var container = $(this);
            var data = container.data('columns');
            var html = '<tr>'
                 data.map(obj => '<th>'   obj.header   '</th>').join('')
                 '</tr>';
            console.log('html: ' html);
            container.append(html);
        });
        return this;
    }
}( jQuery ));

$('#myTable').myPlugin()
#myTable th {
  border: 1px gray solid;
  padding: 1px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" data-columns='[{ "header": "Header1" },
    { "header": "Header2" },
    { "header": "Header3" }]'>
  </table>

Note the .filter('table'), which makes sure the code is only applied to tables.

  • Related