简体   繁体   中英

Getting the collection in a jQuery plugin

Basically, what I am trying to do is create a bbcode editor with a textbox, some buttons and jQuery. Here is my form:

<div class="form-group">
    <div class="btn-group btn-group-sm">
        <button type="button" class="btn glyphicon bbcode" rel="bold"><b>B</b></button>
        <button type="button" class="btn glyphicon bbcode" rel="italic"><i>I</i></button>
    </div>

</div>
<div class="form-group">
    <textarea class="bbcode" rel="editor" cols="100" rows="12"></textarea>
</div>

and my plugin is called using:

<script>
    $('document').ready(function() {
        $('.bbcode').bbcode();
    });
</script>

and the plugin itself, I am just trying to get the basics done at the minute to update the textbox data when a button is clicked:

(function($) {
    "use strict";

    $.fn.bbcode = function() {

        this.click(function() {
            var rel = $(this).attr('rel');
            if (rel == 'editor') {
                return this;
            } else {
                alert($(this).attr('rel'));  // I can see this pop up so the click event is firing
                $('.bbcode[rel=editor]').val('test');
                return this;
            }
        });
    }
} (jQuery));

This seems to be the only way I can pick up the textbox, I don't really want to hardcode the class I want like that. I think what I am looking for is a way to get the collection from the function call in the script tags.

This is more than likely something stupid/obvious I have overlooked.

The value of this in the immediate function refers to the collection. However, it is shadowed by the this inside your click handler (which refers to the element being clicked) so you cannot access it.

Create a variable to store this and that'll be your collection.

(function ($) {
    "use strict";

    $.fn.bbcode = function () {
        var $editors = this;
        this.click(function () {
            var rel = $(this).attr('rel');
            if (rel == 'editor') {
                return this;
            } else {
                alert($(this).attr('rel')); // I can see this pop up so the click event is firing
                $editors.val('test');
                return this;
            }
        });
    }
}(jQuery));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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