简体   繁体   English

如何隔离同一页面中多个jQuery插件之间的功能

[英]How to isolate functionalities between multiple jQuery Plugins in Same Page

If I have more than 1 instance of the same plugin on the same page how can I separate functionality. 如果我在同一页面上有多个相同插件的实例,我该如何分离功能。 eg. 例如。 in this demo http://jsfiddle.net/3jwAK/ , I have a plugin " editor " that appends a link simulating some plugin/widget button, that when clicked will append a line to the textarea . 在这个演示http://jsfiddle.net/3jwAK/中 ,我有一个插件“ editor ”,它附加了一个模拟一些插件/小部件按钮的链接,点击它时会在textarea添加一行。

The problem with it currently is it only targets the last textarea 它目前的问题是它只针对最后一个textarea

Code looks like 代码看起来像

JS JS

(function($) {
    $.fn.editor = function(options) {
        var helpers = {
            rand: function() {
                return Math.round(Math.random() * 20);
            }   
        };

        return this.each(function() {
            $this = $(this);

            var div = $("<a>", {
                text: "Add Random Number",
                href: "#",
                click: function() {
                    $this.val( $this.val() + "\n" + helpers.rand() );
                }
            });

            $this.before(div);
        });

    }
})(jQuery);

HTML HTML

<textarea name="txtArea1" cols="50" rows="6" id="editor1"></textarea>


The problem is the variable $this needs to be a local copy in each run of that function. 问题是变量$this需要在该函数的每次运行中都是本地副本。 Put var in front of it. var放在它前面。

var $this = $(this);

Updated: http://jsfiddle.net/3jwAK/1/ 更新: http//jsfiddle.net/3jwAK/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM