尝试在点击时加载外部插件无效

时间:2018-08-21 14:30:41

标签: javascript asynchronous dropzone.js

我想要实现的是,当我单击按钮时,将创建并显示一个包含Dropzone.js表单的覆盖div。

这是我之前使用的“普通”脚本,一切正常。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Title</title>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
</head>

<body>
    <h1>Upload your files</h1>
    <form action="uploads" method="post" enctype="multipart/form-data" class="dropzone" id="my-dropzone">
    </form>

  <script src="//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js"></script>

<script>
  Dropzone.options.myDropzone = {
            paramName: 'file',
            maxFilesize: 1, // MB
            maxFiles: 1,
            acceptedFiles: ".jpg",
            dictDefaultMessage: "Either drag your files or click",
            addRemoveLinks: true
        };
</script>

</body>
</html>

这是不起作用的脚本:

$(document).ready(function () {
    /**
     * Promises to load the Dropzone.js files on CDNs
     */ 
    function myAsyncFunction(type, url) {
        return new Promise(function (resolve, reject) {
            if (type === "js") {
                var script = document.createElement("script");
                script.src = url;
                script.type = "text/javascript";
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            } else if (type === "css") {
                var link = document.createElement("link");
                link.rel = "stylesheet";
                link.href = url;
                link.onload = resolve;
                link.onerror = reject;
                document.head.appendChild(link);
            }
        })
    }
    
    /**
     * Overlay div
     */
    var uploadDiv = function (__callback) {
        var div = document.createElement('div');
        div.setAttribute('id', 'dropzone-container');
        document.body.appendChild(div);

        var h1 = document.createElement('h1');
        h1.textContent = "Upload file";
        div.appendChild(h1);

        var form = document.createElement('form');
        form.setAttribute('action', 'uploads');
        form.setAttribute('method', 'post');
        form.setAttribute('enctype', 'multipart/form-data');
        form.setAttribute('class', 'dropzone');
        form.setAttribute('id', 'my-dropzone');
        div.appendChild(form);

        __callback();
    };
    
    /**
     * Does the job and call the Dropzone object
     */
    var upload = function () {
        //  Get data-options
        var options = JSON.parse(this.dataset.options);

        //  Create HTML
        uploadDiv(function () {
            myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
                .then(
                    myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
                        .then(
                            Dropzone.options.myDropzone = {
                                paramName: 'file',
                                maxFilesize: options.maxFilesize, // MB
                                maxFiles: options.maxFiles,
                                acceptedFiles: options.acceptedFiles,
                                dictDefaultMessage: "Either drag your files or click",
                                addRemoveLinks: true
                            }
                        )
                )
        });
    }
    
    /**
     * Attach EventListener.
     * @type {HTMLCollectionOf<Element>}
     */
    var btnUpload = document.getElementsByClassName('mb-upload');
    for (var i=0; i<btnUpload.length; i++) {
        btnUpload[i].addEventListener("click", upload);
    }
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Title</title>
</head>

<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">

</body>
</html>

如您所见,创建了div并加载了Dropzone.js文件,但是Dropzone表单无法像上一个代码片段那样工作。

我在哪里错了?

1 个答案:

答案 0 :(得分:1)

您遇到语法错误,

myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js').then(()=>{
    //resolve function
})

$(document).ready(function () {
    /**
     * Promises to load the Dropzone.js files on CDNs
     */ 
    function myAsyncFunction(type, url) {
        return new Promise(function (resolve, reject) {
            if (type === "js") {
                var script = document.createElement("script");
                script.src = url;
                script.type = "text/javascript";
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            } else if (type === "css") {
                var link = document.createElement("link");
                link.rel = "stylesheet";
                link.href = url;
                link.onload = resolve;
                link.onerror = reject;
                document.head.appendChild(link);
            }
        })
    }
    
    /**
     * Overlay div
     */
    var uploadDiv = function (__callback) {
        var div = document.createElement('div');
        div.setAttribute('id', 'dropzone-container');
        document.body.appendChild(div);

        var h1 = document.createElement('h1');
        h1.textContent = "Upload file";
        div.appendChild(h1);

        var form = document.createElement('form');
        form.setAttribute('action', 'uploads');
        form.setAttribute('method', 'post');
        form.setAttribute('enctype', 'multipart/form-data');
        form.setAttribute('class', 'dropzone');
        form.setAttribute('id', 'my-dropzone');
        div.appendChild(form);

        __callback();
    };
    
    /**
     * Does the job and call the Dropzone object
     */
    var upload = function () {
        //  Get data-options
        var options = JSON.parse(this.dataset.options);

        //  Create HTML
        uploadDiv(function () {
            myAsyncFunction('css', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css')
                .then(
                   myAsyncFunction('js', '//cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js')
                        .then(()=>{
                            Dropzone.options.myDropzone = {
                                paramName: 'file',
                                maxFilesize: options.maxFilesize, // MB
                                maxFiles: options.maxFiles,
                                acceptedFiles: options.acceptedFiles,
                                dictDefaultMessage: "Either drag your files or click",
                                addRemoveLinks: true
                            }
                              })
                )
        });
    }
    
    /**
     * Attach EventListener.
     * @type {HTMLCollectionOf<Element>}
     */
    var btnUpload = document.getElementsByClassName('mb-upload');
    for (var i=0; i<btnUpload.length; i++) {
        btnUpload[i].addEventListener("click", upload);
    }
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Title</title>
</head>

<body>
<input type="button" class="form-control btn btn-warning mb-upload" data-options='{"maxFilesize":1,"maxFiles":1,"acceptedFiles":".jpeg,.jpg,.png,.gif"}' id="author_avatar" value="Upload...">

</body>
</html>