繁体   English   中英

在同一页面上两次启动自定义JavaScript插件时,如何解决“未捕获的TypeError:tagsInput不是构造函数”错误

[英]How to fix 'Uncaught TypeError: tagsInput is not a constructor' error while initiating custom JavaScript plugin two times on the same page

我创建了一个标签输入Vanilla JS插件。 当我第一次启动它时,它工作正常。 但是当我重新启动另一个输入标签时。 它将引发以下错误: Uncaught TypeError: tagsInput is not a constructor

Codepen上的有效插件代码

我现在已经从插件中删除了多余的代码。

插入:

    (function () {
                var tagsInput = function (opts) {
                    this.arr = [];
                    this.input = document.createElement("input");
                    this.wrapper = document.createElement("div");
                    this.options = Object.assign(tagsInput.defaults, opts);
                    this.originalInput = document.getElementById(opts.selector);
                    buildUI(this);
                    addEvents(this);
                }

                function buildUI(tags) {
                    //build UI code here
                }

                function addEvents(tags) {
                    // add events to tags here
                }

                tagsInput.prototype.addTag = function (str) {
                    // add tags code 
                }

                tagsInput.prototype.deleteTag = function (tag, i) {
                    // delete tags code
                }

                tagsInput.prototype.anyError = function (str) {
                    // find errors
                }

                tagsInput.prototype.addData = function (data) {
                    // add prefill data
                }

                tagsInput.defaults = {
                    selector: '',
                    duplicate: false,
                    max: null,
                    wrapperClass: 'tags-input-wrapper',
                    tagsClass: 'tag'
                }
                //make it global
                window.tagsInput = tagsInput;
            })();

当我在同一页面上对其进行两次初始化时,将引发错误。

初始化插件:

            var tagsInput = new tagsInput({
                selector: 'demoInput',
                duplicate: false,
                max: 4,
                wrapperClass: 'tags-input-wrapper',
                tagsClass: 'tag'
            });
            tagsInput.addData(["aloo", "bhindi", "tamater"]);

您分配tagsInput到的实例tagsInput 现在,当您引用它时,它将是tagsInput的实例, tagsInput不是构造函数。 您可以通过将var tagsInput = new tagsInput({更改为以下内容来修复此问题: var tagsInputOne = new tagsInput({var demoInput = new tagsInput({

希望这会有所帮助。

您正在将tagsInput重新分配给tagsInput构造的tagsInput -这样将只工作一次,然后,因为不再有对旧tagsInput构造函数的引用,将对其进行垃圾回收。 更改变量名称:

var demoInput = new tagsInput({...});

或将tagsInput更改为大写,如构造函数命名约定所示:

var TagsInput = function(opts) {...}

暂无
暂无

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

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