Jquery多图上传预览功能

我的input标签是append出来的。

var content = "...此处省略...";
content+= "<input type='file' name='filename' onchange='previewFile(this)'>";

$('#TableFile').append(content);

我现在遇到的问题是this对象无法传到方法里来

function previewFile(obj){
    var file = obj.files[0]
    console.log(file)
}

浏览器会报错无法捕获对象Uncaught TypeError: Cannot read property 'files' of undefined

我是jquery新手,在做的东西是Jquery图片上传预览的效果

感觉是在onchange='previewFile(this)'这里写的不对,哪位大神指点一下?


谢谢回答问题的大家, 我索性把代码所有代码贴出来,你们就知道我在干嘛了。

我现在添加多个input上传,每次图片都只能改变第一个,不知道咋弄

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Html Test_1</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="position: relative">
    <input type="checkbox" id="imgBox1" style="float: left">
    <input type="text" placeholder="请输入名称" style="float: left">
</div><br>
<div class="imgBox1" style="display: none">
    <form action="" id="FormFile1" method="post" enctype="multipart/form-data">
        <table id="TableFile1"></table>
    </form>
</div>
<br>
<input type="button" name="submit" value="保存" id="submit" onclick="getVal()">
</body>
<script>
    /**
     * 将新建的imgBox框封装起来
     **/
    function newImgBox(id) {
        console.log("方法接受到的"+ id)
        var action = "<input id='ButtonAdd"+id+"'  type='button' value='增加'>";
        action += "<input id='ButtonSubtract"+id+"'  type='button' value='减少'>";
//        action += "<input id='SumbitUpload"+id+"'  type='button' value='Upload'>";
        $('#TableFile'+ id).append(action);


        $("#ButtonAdd"+id).on("click", function () {
            var content = "<tr style='vertical-align:middle;'><td>";
            content += "<input type='checkbox' name='cbk' />";
            content += "<input type='file' name='filename"+id+"' onchange='previewFile(this)' id='filename"+id+"-"+imgId+"'>";
            content += "<img src='' height='200' width='200'>";
            content += "</td></tr>";
            $("#TableFile" + id).append(content);
            previewFile();
        });

        $("#ButtonSubtract"+id).on("click", function () {
            $('input[name="cbk"]').each(function () {
                if (this.checked) {
                    $(this).closest('tr').remove();
                }
            });
        });

        $("#SubmitUpload"+id).on('click', function () {
            $('#FormFile').attr('action', 'DynamicUploadFiles');
            $("#FormFile").submit();
        });
    }


        /**
         *第一个CheckBox
         * 选中时将Table追加进form
         * 取消时将Table删除,这样确保重复点击CheckBox时,table始终保持一个
         **/
        $('#imgBox1').on('click',function () {
            var id = 1;
            if($("#imgBox1").is(":checked")){//选中
                $('.imgBox1').css('display','block');
//                $('#FormFile'+ id).append("<table id='TableFile"+id+"'></table>");  该方法错误,暂时废弃
                newImgBox(id);  //第一个选项框ID传1
                return;
            }else{
                $('#TableFile' + id).empty();
                $('.imgBox1').css('display','none');
                return;
            }

        })
        /**
         *第二个CheckBox
         **/
        $('#imgBox2').bind('click',function () {
            var id = 2;
            if($("#imgBox2").is(":checked")){//选中
                console.log(1)
                $('.imgBox2').css('display','block');
//                $('#FormFile'+ id).append("<table id='TableFile"+id+"'></table>");
                newImgBox(id);  //第2个选项框ID传2
            }else{
                console.log(2)
                $('#TableFile' + id).empty();
                $('.imgBox2').css('display','none');
            }
        })


        //定义getVal方法
        var getVal = function () {
            var $inputArr = $('input[name = "filename1"]:not(:first-child)');
            var $bigImg = $('input[name = "filename1"]:first-child')
            var $inputArr2 = $('input[name = "filename2"]');
//            console.log($inputArr)
            var result = [];
            var result2 = [];
            $inputArr.each(function () {
                result.push($(this).val())
            });
            result.push($bigImg)
            $inputArr2.each(function () {
                result2.push($(this).val())
            })
            console.log(result)
            console.log(result2)
        }

        /**
         * 封装一个预览图片的方法
         *
         * 这里有一个疑问,我想每个input的图片单独显示在img标签里,这里我不会控制
         */
        function previewFile(obj,id){
            console.log(obj)
            var file = obj.files[0];
            console.log(file)
            console.log('previewFile接受到的id是:' + id);
            var preview = document.getElementById(obj.id).nextElementSibling;  
            var reader = new FileReader();
            reader.onloadend = function () {
                preview.src = reader.result;
            }
            if (file){
                reader.readAsDataURL(file);
            }else{
                preview.src = ''
            }
        }

</script>
</html>
阅读 4.1k
5 个回答

clipboard.png

这个去掉,你这里点击添加只是添加了html结构,并没有上传文件,所以会提示undefined

clipboard.png

代码没错的,看看的报错的 console.log(obj),完整代码看看

clipboard.png

同样的操作为什么这里可以打印出结果

代码没毛病,this传不进去。console obj也肯定是undefined 问题应该没出在这段代码中

content+= "<input type='file' name='filename' onchange='previewFile(this)'>";
上面那句换成这样
content+= "<input type='file' name='filename' onchange='previewFile("+this+")'>";
试一下 。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题