jquery插件开发,如何保存创建的元素的引用.

目前需求是用div元素实例化插件,在插件里创建一个input[type='file'],一个input[type='text']和button,input[type='text']的值为input[type='file']选择的文件名,在this上定义属性,把文件上传赋值给this.fileInput,调用自定义方法输出this.fileInput.files[0],输出值却为div元素.请问在闭包里如何保存使用创建的元素.代码如下:
;(function ($) {

    var hideFile;
    hideFile = (function () {
        function hideFile(element, options) {
            this.$div = $(element);
            this.settings = $.extend({}, $.fn.hideFile.defaults, options);
            this.settings = $.extend({}, $.fn.hideFile.defaults, this.$div.data(), options);
            this.init();
        }
        hideFile.prototype = {
            init: function () {
                var file = document.createElement('input');
                file.type = 'file';
                file.style.display = 'none';
                this.fileInput = file;
                var input = document.createElement('input');
                input.type = 'text';
                input.disabled = true;
                var button = document.createElement('button');
                button.type = 'button';
                button.innerText = 'select';
                this.$div.append(file, input, button);
                button.onclick = function () {
                    file.click();
                };
                file.onchange = function () {
                    var value = this.value;
                    if (value)
                        value = file.files[0].name;
                    input.value = value;
                };
                console.log(this.fileInput);
                console.log('init');
            },
            getFiles: function () {
                console.log('getFiles');
                return this.fileInput.files;
            }
        };
        return hideFile;
    })();

    $.fn.hideFile = function (options) {
        return this.each(function () {
            var $me = $(this),
                instance = $me.data('plugin');
            //将实例后的插件缓存在dom里
            if (!instance) {
                $me.data('plugin', new hideFile(this, options));
            }
            //如果options是字符串,则调用方法options
            //$('#id').plugin('dosomething')即$('#id').plugin.dosomething()
            if ($.type(options) === 'string') instance[options]();
        })
    };
    $.fn.hideFile.defaults = {
        textAttrs: {
            className: 'default'
        },
        buttonAttrs: {
            text: 'select',
            className: ''
        }
    };
    $(function () {
        return new hideFile($('[data-plugin]'));
    });
})(jQuery);
阅读 1.8k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进