Set counter per element in jQuery plugin

前端 未结 3 1345
难免孤独
难免孤独 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: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
        });
    };
    

提交回复
热议问题