无法访问javascript自定义对象中函数内的元素

时间:2018-09-19 13:57:18

标签: javascript

运行此代码时,它将生成适当的文件上载ui,并将事件侦听器添加到上载按钮。但是,上载函数的第一行为此this.missingFile引发错误-无法读取未定义的属性'style'。我在这里做什么错了?

function FileUploader(props) {
    var div = document.querySelector(props.element);

    var uid = generateGuid();

    var templateHtml = "<p><div id=\"dvMissingFile-" + uid + "\" class=\"missing-file\"> Please choose a file.</div><input type=\"file\" id=\"flUploadedFile-" + uid + "\" name=\"flUploadedFile-" + uid + "\"/></p><div class=\"dvProgressBar\" id=\"progress-" + uid + "\"><div></div></div>";
    div.innerHTML = templateHtml;

    this.uploadButton = document.querySelector(props.uploadButton);
    this.fileInput = document.querySelector("#flUploadedFile-" + uid);
    this.missingFile = document.querySelector("#dvMissingFile-" + uid);
    this.progress = document.querySelector("#progress-" + uid);
    this.url = props.postUrl;

    this.upload = function() {
        this.missingFile.style.display = "none";

        if (this.fileInput.files.length === 0) {
            this.missingFile.style.display = "";
        }
        else {
            var file = this.fileInput.files[0];
            var xhr = new XMLHttpRequest();
            var pbar = document.querySelector("#progress-" + uid + ">div");
            if (xhr.upload) {

                // do upload
            }
        }
    }

    this.uploadButton.addEventListener("click", this.upload);
}

用法示例

<div id="dvUploader"></div>
<button type="button" id="btnUpload" class="btn btn-primary">Upload</button>
<script>
var uploader = new FileUploader({
                    element: "#dvUploader",
                    uploadButton: "#btnUpload",
                    postUrl: "myposturl"
});
</script>

1 个答案:

答案 0 :(得分:1)

对代码进行一次小的更新可以帮助:

    this.upload = function() {
// ...
    }.bind(this);