Set counter per element in jQuery plugin

前端 未结 3 1339
难免孤独
难免孤独 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: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

提交回复
热议问题