在jQuery插件中为每个元素设置计数器 [英] Set counter per element in jQuery plugin

查看:113
本文介绍了在jQuery插件中为每个元素设置计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在jQuery插件中设置计数器时,将针对插件的每个实例进行设置.例如

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 = function (el) {
    var counter = 0;
    $(el).click(function () {
        counter++;
        console.log(counter);
    });
};

将启动两个计数器. (在此处尝试)但是,我想为每个设置一个计数器元素,而不是每个实例.因此,在小提琴中,我总共需要三个计数器. (请注意,元素的长度不是预先设置的,因此必须是动态的.)我考虑过要在计数器名称中添加唯一值,但是我不完全确定哪个值足够具体,以便可以从不重复.

Will initiate two counters. (Try it here) However, I'd like to have one counter for each element rather than each instance. So, in the fiddle I'd need three counters in total. (Note that the length of elements isn't set in advance so it has to be dynamic.) I thought about adding a unique value to the counter's name, but I'm not entirely sure what value is specific enough so that there can never be any duplicates.

也许是for循环和一个整数来区分,例如counter-1counter-2counter-3?但是,如何遍历该插件的实例?换句话说,如何确保在总共三个元素上两次按小提琴形式调用插件时,我只得到三个 unique 计数器?

Maybe a for loop and an integer to make a distinction, e.g. counter-1, counter-2, counter-3? But how do I loop over instances of the plugin? In other words, how do I make sure that when calling the plugin twice as in the fiddle on three elements in total, I only get three unique counters?

推荐答案

您可以使用 .data() 自定义与您的图元相关联

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.

代码

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

演示

我个人想这样

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

    });
};

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

演示

这篇关于在jQuery插件中为每个元素设置计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆