JavaScript运行错误的事件侦听器功能

时间:2018-08-09 14:59:23

标签: javascript html

当我将文件上传到card2 html div时,我希望运行FileUpload2 javascript函数而不是FileUpload。但是我的输出正在运行console.log("Hello");而不是console.log("World");,表明调用了FileUpload函数,而不是FileUpload2

var imgPreview = document.getElementById('img-preview');
var fileUpload = document.getElementById('file-upload');

var imgPreview2 = document.getElementById('img-preview2');
var fileUpload2 = document.getElementById('file-upload2');

fileUpload.addEventListener('change', function(event){
        var file = event.target.files[0];
        var formData = new FormData();
        formData.append('file', file);
        formData.append('upload_preset', CLOUDINARY_UPLOAD_PRESET);
        axios({
            url: CLOUDINAY_URL,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: formData
        }).then(function(res){
            console.log("Hello");
            console.log(res);
            imgPreview.src = res.data.secure_url;
        }).catch(function(err){
            console.log(err);
        });
    });

    fileUpload2.addEventListener('change', function(event){
        var file2 = event.target.files[0];
        var formData2 = new FormData();
        formData.append('file', file2);
        formData.append('upload_preset', CLOUDINARY_UPLOAD_PRESET2);
        axios({
            url: CLOUDINAY_URL,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: formData2
        }).then(function(res){
            console.log("World");
            console.log(res);
            imgPreview2.src = res.data.secure_url;
        }).catch(function(err){
            console.log(err);
        });
    });
<div class="card">
    <img  src="{{url_for('static', filename='css/images/mount2.png')}}" id="img-preview" />
    <label class="file-upload-container" for="file-upload">
        <input id="file-upload" type="file" style="display:none;">

    </label>
</div>
<div class="card2">
    <img  src="{{url_for('static', filename='css/images/mount2.png')}}" id="img-preview2" />
    <label class="file-upload-container2" for="file-upload">
        <input id="file-upload2" type="file" style="display:none;">

    </label>
</div>

1 个答案:

答案 0 :(得分:1)

更改

<label class="file-upload-container2" for="file-upload">

<label class="file-upload-container2" for="file-upload2">