How to isolate functions between multiple jQuery plugins in the same page

If I have more than one instance of the same plugin on the same page, how can I separate the functionality. eg. in this demo http://jsfiddle.net/3jwAK/ , I have a plugin " editor" that adds a link that mimics some plugin / widget button, which when clicked will add a line to textarea.

The problem with this currently is that it only targets the last textarea

The code looks like

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

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


+1
source share
1 answer

, $this . var .

var $this = $(this);

: http://jsfiddle.net/3jwAK/1/

+4

Source: https://habr.com/ru/post/1794984/


All Articles