Set counter per element in jQuery plugin

前端 未结 3 1340
难免孤独
难免孤独 2021-01-28 07:11

When you set a counter in a jQuery plugin it will be set per instance of the plugin. For instance

$.myPlugin(\".one\");
$.myPlugin(\".two\");

$.myPlugin = funct         


        
相关标签:
3条回答
  • 2021-01-28 07:21

    Use custom data- attributes to set a counter

    $('button').each(function(){
        $(this).attr('data-counter', 0);
        $(this).click(function () {
            var counter = parseInt($(this).attr('data-counter'));
            counter++;
            console.log(counter);
            $(this).attr('data-counter', counter);
        });
    });
    

    DEMO

    0 讨论(0)
  • 2021-01-28 07:27

    Use .data()
    Try this example:

    $.myPlugin(".one");
    $.myPlugin(".two");
    
    $.myPlugin = function (el) {
        $(el).on('click', function () { // using .on instead of .click to handle dynamicaly added elements
            var counter = parseInt($(this).data('counter')); // using .data() function of jquery to get value from element, it uses data-counter attribute
            counter++; // iterating
            $(this).data('counter', counter); // setting back counter with iterated value
        });
    };
    
    0 讨论(0)
  • 2021-01-28 07:31

    You can use .data() to custom associated with your elemet

    Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

    Code

    $.myPlugin = function (el) {
        $(el).click(function () {
            var counter = $(this).data('counter') || 1;
            console.log(counter);
            $(this).data('counter', ++counter);
        });
    };
    

    DEMO

    I personally would like it this way

    $.fn.myPlugin = function () {
        this.click(function () {
            var counter = $(this).data('counter') || 1;
            console.log(counter);
            $(this).data('counter', ++counter)
    
        });
    };
    
    $(".one").myPlugin();
    $(".two").myPlugin();
    

    DEMO

    0 讨论(0)
提交回复
热议问题