如何为jQuery插件设置私有变量? [英] How to set a private variable for a jQuery plugin?

查看:56
本文介绍了如何为jQuery插件设置私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个简单的插件,它可以将元素的文本作为默认值使用,或者您可以在调用插件时设置此值。

I would like to create a simple plugin, which works with the text of the element as a default value, or you can set this value, when you call the plugin.

但是如果我没有设置值,并为多个元素调用插件,则默认值会成倍增加。

But if I don't set the value, and call the plugin for more than one element, the default value getting multiplied.

(function($) {
    $.fn.reText = function(options) {
        var settings = $.extend({
            label : $(this).text()
        }, options);
        return this.each(function() {
            $(this).text(settings.label);
        });
    };
})(jQuery);

致电:

$(function() {
    $('div').reText();
});

结果:

<div>text 1</div>
<div>text 2</div>

jsFiddle

我知道,问题是设置的范围,但我不知道如何解决问题...

I know, the problem is the settings's scope, but I don't know how to resolve the problem...

推荐答案

在每个函数内部移动设置变量声明,以便它每个元素/ div都会有所不同。

Move the settings variable declaration inside of each function, so that it will different for each element / div.

示例代码如下:

 return this.each(function() {
    var settings = $.extend({
      label : $(this).text()
    }, options);

    $(this).text(settings.label);
 });

更新小提琴

这篇关于如何为jQuery插件设置私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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