JQuery 插件可以在 JQuery 方法链上调用,还是需要在选择器之后直接调用

Can a JQuery plugin be called on a JQuery chain of methods or does it need to be called straight after a selector?

本文关键字:JQuery 调用 选择器 之后 方法 插件      更新时间:2023-09-26

我很难让我的文本区域自动垂直扩展。

我有一些代码可以帮助使文本区域自动垂直扩展,并且由于某种原因,当我清理所有JS并提供参考文本区域的选择器时,它可以工作,例如 $('textarea').autoGrow() ;

在方法链上调用插件会阻止它工作。 例如

micropostBox.hide().removeClass("micropost_content")
.addClass("micropost_content_expanded").show().autoGrow();

我建立了插件代码工作,因此将所有工作代码复制到同一页面并将autoGrow代码应用于我的textarea但它似乎没有响应。我注意到我正在使用代码的插件使用绑定和解绑方法。在我的代码中,我使用了JQuery的 on 和 off 方法,并想知道这是否可能是我的textarea自动调整大小不起作用的原因?

这是代码:http://jsfiddle.net/erU5J/101/

自动增长插件 js 代码

$(function($) {
    $.fn.autoGrow = function() {
        return this.each(function() {
            var txtArea = $(this);
            var colsDefault = txtArea.attr('cols');
            var rowsDefault = txtArea.attr('rows');
            var updateSize = function() {
                var linesCount = 0;
                var lines = txtArea.attr('value').split(''n');
                for (var i = lines.length - 1; i >= 0; --i) {
                    linesCount += Math.floor((lines[i].length / colsDefault) + 1);
                }
                if (linesCount >= rowsDefault) {
                    txtArea.attr('rows', linesCount + 1);
                }
                else {
                    txtArea.attr('rows', rowsDefault);
                }
            };
            txtArea.unbind('.autoGrow').bind('keyup.autoGrow', updateSize).bind('keydown.autoGrow', updateSize).bind('change.autoGrow', updateSize);
        });
    };
});

我的 js 代码

$(function() {
    $("div.microposts").on("focus", "textarea#micropostBox", function() {
        var micropostForm = $(this).parent(),
            micropostBox = micropostForm.find('textarea#micropostBox'),
            micropostButton = micropostForm.find("input#micropostButton"),
            xButton = micropostForm.find("div.xButton");

        micropostBox.prop('rows', 7);
        micropostForm.find('div#micropostOptions').removeClass('micropostExtraOptions');
        micropostForm.find('div#postOptions').show();
        $.trim(micropostBox.val()) == '' ? micropostButton.addClass("disabledMicropostButton").show()
        :
        micropostButton.prop('disabled', false);
        micropostBox.hide().removeClass("micropost_content").addClass("micropost_content_expanded").show().autoGrow();
        xButton.show();
        micropostButton.prop('disabled', true);

        micropostBox.off().on("keypress input change", function() {
            micropostButton.prop({
                disabled: !$.trim($(this).val()) != ''
            });
            $.trim($(this).val()) != '' ? micropostButton.removeClass("disabledMicropostButton").addClass("activeMicropostButton")
            :
            micropostButton.removeClass("activeMicropostButton").addClass("disabledMicropostButton");
        });
        xButton.on('click', function() {
            micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
            micropostForm.find('div#micropostOptions').addClass('micropostExtraOptions');
            micropostBox.val("");
            micropostForm.find('div#postOptions').hide();
            xButton.hide();
            micropostButton.hide();
            micropostBox.removeAttr('style');
            micropostBox.prop('rows', 0);
            micropostForm.find('.imagePreview > img').remove();
            micropostForm.find('.imagePreview').hide();
        });
    });
});


$(function() {
    $('div.microposts').on('click', 'li#addImage', function() {
        var form = $(this).parents('form#new_micropost'),
            fileField = form.find('input#micropost_image');
        fileField.trigger('click');
    });
});
$(function() {
    $('input#micropost_image').change(function(evt) { //.off() make sautoresize work
        var image = evt.target.files[0],
            form = $(this).parents('form#new_micropost'),
            imagePreviewBox = form.find('div.imagePreview'),
            reader = new FileReader();
        reader.onload = function(evt) {
            var resultdata = evt.target.result,
                img = new Image();
            img.src = evt.target.result;
            imagePreviewBox.show().prepend(img);
        };
        reader.readAsDataURL(image);
    });
});​

文本区域

 <textarea class="micropost_content" cols="40" id="micropostBox" name="micropost[content]" placeholder="" rows="0"></textarea>

最好在 jsfiddle 上查看一个工作示例。我的目标是使用文本区域中的图像上传按钮在将图像添加到页面之前和之后自动调整文本区域的大小。

亲切问候

这取决于插件调用之前的方法是否返回了包含需要附加插件的元素的 jQuery 对象。

下面是一些返回和不返回您开始使用的元素的方法示例:

$('element')           //get an element
    .contents()        //get an elements contents
    .wrapAll('<div>')  //wrapAll contents with div and returns the contents, not wrapper
    .parent()          //the wrapper
    .parent()          //the element
    .myPlugin()        //we attach a plugin to element
$('<div>')
    .appendTo('body')  //appendTo returns the same element, the div
    .myPlugin()        //attaches to the div
$('element')           //get an element
    .text()            //get its text
    .myPlugin()        //chaining isn't possible since text() returns a string

最好阅读jQuery中每个方法的文档以及它返回的内容。一些 DOM 方法通常返回相同的元素,有些不返回,有些不返回元素而是返回值。

综上所述,插件可以在链之后附加吗?是的,这取决于。

参考 jQuery 的文档

http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability