清除使用jquery从阵列中删除的图像预览文件

清除使用jquery从阵列中删除的图像预览文件,jquery,Jquery,我已经想了一个多月了。单击预览器上的“x”后,我无法将图像从阵列中删除 我尝试使用接头失败 $('#list').on('click', '.remove_img_preview',function () { $(this).parent('span').remove(); //this is not working... var i = array.indexOf($(this)); if(i != -1) {

我已经想了一个多月了。单击预览器上的“x”后,我无法将图像从阵列中删除

我尝试使用接头失败

$('#list').on('click', '.remove_img_preview',function () {
        $(this).parent('span').remove();

        //this is not working...
        var i = array.indexOf($(this));
        if(i != -1) {
            array.splice(i, 1);
        }
        // tried this too:
        //$(this).parent('span').splice( 1, 1 );

        count--;
    });
请帮帮我

编辑:

我需要将其从数组或输入文件列表中删除的原因是,在提交表单时,它应该只上载预览器中的图像,而不上载从预览器中删除的图像

示例:如果我上载image1、image2、image3,然后删除image2,则提交时应仅上载image1和image3。

var $fileUpload = $("#files"),
    $list = $('#list'),
    thumbsArray = [],
    maxUpload = 5;

// READ FILE + CREATE IMAGE
function read( f ) {
  return function( e ) {
    var base64 =  e.target.result;
    var $img = $('<img/>', {
      src: base64,
      title: encodeURIComponent(f.name), //( escape() is deprecated! )
      "class": "thumb"
    });
    var $thumbParent = $("<span/>",{html:$img, "class":"thumbParent"}).append('<span class="remove_thumb"/>');
    thumbsArray.push(base64); // Push base64 image into array or whatever.
    $list.append(  $thumbParent  );
  };
}

// HANDLE FILE/S UPLOAD
function handleFileSelect( e ) {
    e.preventDefault(); // Needed?
    var files = e.target.files;
    var len = files.length;
    if(len>maxUpload || thumbsArray.length >= maxUpload){
      return alert("Sorry you can upload only 5 images");
    }
    for (var i=0; i<len; i++) { 
        var f = files[i];
        if (!f.type.match('image.*')) continue; // Only images allowed      
        var reader = new FileReader();
        reader.onload = read(f); // Call read() function
        reader.readAsDataURL(f);
    }
} 

$fileUpload.change(function( e ) {
    handleFileSelect(e);
});

$list.on('click', '.remove_thumb', function () {
    var $removeBtns = $('.remove_thumb'); // Get all of them in collection
    var idx = $removeBtns.index(this);   // Exact Index-from-collection
    $(this).closest('span.thumbParent').remove(); // Remove tumbnail parent
    thumbsArray.splice(idx, 1); // Remove from array
}); 
var$fileUpload=$(“#文件”),
$list=$(“#list”),
thumbsArray=[],
maxUpload=5;
//读取文件+创建图像
函数读取(f){
返回函数(e){
var base64=e.target.result;
var$img=$('”,{html:$img,“类”:“thumbprent”});
thumbsArray.push(base64);//将base64映像推送到数组中或其他任何位置。
$list.append($thumbParent);
};
}
//处理文件的上载
功能手柄文件选择(e){
e、 preventDefault();//是否需要?
var files=e.target.files;
var len=files.length;
如果(len>maxUpload | | thumbsArray.length>=maxUpload){
返回警报(“抱歉,您只能上载5张图像”);
}

对于(var i=0;i根据我在您问题中的理解,您正试图从多文件输入表单中删除一个文件。不幸的是,由于所有浏览器中的安全限制,这是不可能的。多文件输入返回一个只读的文件列表
,其中包含
文件
对象的集合。因此,您可以不能简单地从列表中删除元素(签出问题)

不过,有一种解决方法需要使用AJAX来处理表单。您可以处理
文件列表
并将文件存储在一个数组中。然后在('submit')
函数上附加一个
,该函数将截获提交操作。将发出发送序列化表单的
$.AJAX()
请求,而不是提交事件

例如:

<!-- upload.html -->
<!DOCTYPE html>
<html>
<head lang="en">
    <title>Upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

    <style type="text/css">
        ul{
            width: 650px;
        }
        ul li {
            list-style: none;
            width: 165px;
            float:left;
            position: relative;
            margin: 0px 0px 0px 20px;
        }

        .thumb {
            width: 150px;
        }

        .remove {
            position: absolute;
            top: 0px;
            right: 0px;
            color: red;
            cursor: pointer;
        }

        /* Prettify json output.. not needed in your code */
        pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
        .string { color: green; }
        .number { color: darkorange; }
        .boolean { color: blue; }
        .null { color: magenta; }
        .key { color: red; }

    </style>

    <script type="text/javascript">
        $(document).ready(function() {
            // You don't need this - it's used only for the demo.
            function jsonPrettify(json) {
                if (typeof json != 'string') {
                    json = JSON.stringify(json, undefined, 2);
                }
                json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                    var cls = 'number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'key';
                        } else {
                            cls = 'string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'boolean';
                    } else if (/null/.test(match)) {
                        cls = 'null';
                    }
                    return '<span class="' + cls + '">' + match + '</span>';
                });
            }
            // You don't need this - it's used only for the demo.



            // The code
            var filesArray = [];

            /**
             * This function processes all selected files
             *
             * @param e eventObject
             */
            function previewFiles( e ) {
                // FileList object
                var files = e.target.files;
                var preview = $('#imagePreviews');

                // Loop through the FileList and render image files as thumbnails.
                for (var i = 0, f; f = files[i]; i++) {

                    // Only process image files.
                    if (!f.type.match('image.*')) {
                        continue;
                    }

                    var reader = new FileReader();

                    // Closure to capture the file information.
                    reader.onload = (function(theFile) {
                        return function(e) {
                            // Render thumbnail.
                            var li = $('<li><img class="thumb" src="'+ e.target.result +'" title="'+ escape(theFile.name) +'"/><div class="remove">X</div></li>');
                            preview.append(li);

                            // Append image to array
                            filesArray.push(theFile);
                        };
                    })(f,preview);

                    // Read the image file as a data URL.
                    reader.readAsDataURL(f);
                }
            }
            // Attach on change to the file input
            $('#fileInput').on('change', previewFiles);

            /**
             * Remove the file from the array list.
             *
             * @param index integer
             */
            function removeFile( index ){
                filesArray.splice(index, 1);
            }
            // Attach on click listener which will handle the removing of images.
            $(document).on('click', '#imagePreviews .remove',function(e){
                var image = $(this).closest('li');

                console.log(image.index());

                // Remove the image from the array by getting it's index.
                // NOTE: The order of the filesArray will be the same as you see it displayed, therefore
                //       you simply need to get the file's index to "know" which item from the array to delete.
                console.log('Files:' ,filesArray);
                removeFile(image.index());
                console.log('Files:' ,filesArray);

                // Fadeout the image and remove it from the UI.
                image.fadeOut(function(){
                    $(this).remove();
                });
            });


            /**
             * This function processes the submission of the form.
             *
             * @param e
             */
            function submitForm(e){
                // Stop the form from actually submitting.
                e.preventDefault();

                // Create a new FormData based on our current form.
                // Makes live easier as we can attach a list of File objects.
                var formData = new FormData($('#myForm')[0]);
                for(var i= 0, file; file = filesArray[i]; i++){
                    formData.append('files[]', file);
                }

                // Send the ajax request.
                $.ajax({
                    url: 'upload.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        $('#response').html(jsonPrettify(response));
                    }
                });
            }
            // Attach on submit to the form submission.
            $('#myForm').on('submit', submitForm);
        });
    </script>

</head>

<body>

    <div style="width: 650px; border: 1px #D8D8D8;">

        <form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
            <label>Name</label>
            <input type="text" name="firstName" value="FirstName"/>
            <input type="text" name="lastName" value="LastName"/>

            <!-- Don't set a name of this input so that we won't need to remove it before serialization. -->
            <input id="fileInput" type="file" value="Upload button" multiple/>

            <div style="width: 600px; border: 1px solid #D8D8D8;">
                <ul style="list-style: none;" id="imagePreviews">
                </ul>

                <div style="clear: both;">&nbsp;</div>
            </div>

            <br>

            <input type="submit"/>

        </form>

        <br>
        Upload.php response<br>
        <pre id="response" style="width: 650px;"></pre>
    </div>

</body>
</html>

上传
保险商实验室{
宽度:650px;
}
ulli{
列表样式:无;
宽度:165px;
浮动:左;
位置:相对位置;
保证金:0px 0px 0px 20px;
}
.拇指{
宽度:150px;
}
.移除{
位置:绝对位置;
顶部:0px;
右:0px;
颜色:红色;
光标:指针;
}
/*美化json输出..代码中不需要*/
前{outline:1px solid#ccc;padding:5px;margin:5px;}
.string{color:green;}
.number{color:darkorange;}
.boolean{color:blue;}
.null{颜色:洋红色;}
.key{颜色:红色;}
$(文档).ready(函数(){
//你不需要这个-它只用于演示。
函数jsonPrettify(json){
if(typeof json!=“string”){
json=json.stringify(json,未定义,2);
}
json=json.replace(//&/g,“&;”).replace(//g,”);
返回json.replace(/(“(\\u[a-zA-Z0-9]{4}\\\[^u]\\\\\\”)*”(\s*:)?\b(true | false | null)\b |-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)/g,函数(匹配){
var cls='数字';
如果(/^”/.test(匹配)){
如果(/:$/.test(匹配)){
cls=‘键’;
}否则{
cls='字符串';
}
}else if(/true | false/.test(匹配)){
cls='布尔';
}else if(/null/.test(匹配)){
cls='null';
}
返回“”+匹配+“”;
});
}
//你不需要这个-它只用于演示。
//代码
var filesArray=[];
/**
*此函数用于处理所有选定的文件
*
*@param e eventObject
*/
函数预览文件(e){
//文件列表对象
var files=e.target.files;
变量预览=$(“#图像预览”);
//循环浏览文件列表并将图像文件渲染为缩略图。
for(var i=0,f;f=files[i];i++){
//仅处理图像文件。
如果(!f.type.match('image.*')){
继续;
}
var reader=new FileReader();
//闭包以捕获文件信息。
reader.onload=(函数(文件){
返回函数(e){
//渲染缩略图。
var li=$(“
  • X
  • ”); 预览。追加(li); //将图像附加到数组 filesArray.push(文件); }; })(f)预览; //将图像文件作为数据URL读取。 reader.readAsDataURL(f); } } //将更改附加到文件输入 $('#fileInput')。在('change',previewFiles')上; /** *从数组列表中删除该文件。 * *@param索引整数 */ 函数removeFile(索引){ 拼接(索引,1); } //单击“附加”侦听器可处理图像的删除。 $(文档).on('单击','图像预览.remove',函数(e){ var image=$(this).closest('li'); console.log(image.index());
    <!-- upload.html -->
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <title>Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    
        <style type="text/css">
            ul{
                width: 650px;
            }
            ul li {
                list-style: none;
                width: 165px;
                float:left;
                position: relative;
                margin: 0px 0px 0px 20px;
            }
    
            .thumb {
                width: 150px;
            }
    
            .remove {
                position: absolute;
                top: 0px;
                right: 0px;
                color: red;
                cursor: pointer;
            }
    
            /* Prettify json output.. not needed in your code */
            pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
            .string { color: green; }
            .number { color: darkorange; }
            .boolean { color: blue; }
            .null { color: magenta; }
            .key { color: red; }
    
        </style>
    
        <script type="text/javascript">
            $(document).ready(function() {
                // You don't need this - it's used only for the demo.
                function jsonPrettify(json) {
                    if (typeof json != 'string') {
                        json = JSON.stringify(json, undefined, 2);
                    }
                    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                        var cls = 'number';
                        if (/^"/.test(match)) {
                            if (/:$/.test(match)) {
                                cls = 'key';
                            } else {
                                cls = 'string';
                            }
                        } else if (/true|false/.test(match)) {
                            cls = 'boolean';
                        } else if (/null/.test(match)) {
                            cls = 'null';
                        }
                        return '<span class="' + cls + '">' + match + '</span>';
                    });
                }
                // You don't need this - it's used only for the demo.
    
    
    
                // The code
                var filesArray = [];
    
                /**
                 * This function processes all selected files
                 *
                 * @param e eventObject
                 */
                function previewFiles( e ) {
                    // FileList object
                    var files = e.target.files;
                    var preview = $('#imagePreviews');
    
                    // Loop through the FileList and render image files as thumbnails.
                    for (var i = 0, f; f = files[i]; i++) {
    
                        // Only process image files.
                        if (!f.type.match('image.*')) {
                            continue;
                        }
    
                        var reader = new FileReader();
    
                        // Closure to capture the file information.
                        reader.onload = (function(theFile) {
                            return function(e) {
                                // Render thumbnail.
                                var li = $('<li><img class="thumb" src="'+ e.target.result +'" title="'+ escape(theFile.name) +'"/><div class="remove">X</div></li>');
                                preview.append(li);
    
                                // Append image to array
                                filesArray.push(theFile);
                            };
                        })(f,preview);
    
                        // Read the image file as a data URL.
                        reader.readAsDataURL(f);
                    }
                }
                // Attach on change to the file input
                $('#fileInput').on('change', previewFiles);
    
                /**
                 * Remove the file from the array list.
                 *
                 * @param index integer
                 */
                function removeFile( index ){
                    filesArray.splice(index, 1);
                }
                // Attach on click listener which will handle the removing of images.
                $(document).on('click', '#imagePreviews .remove',function(e){
                    var image = $(this).closest('li');
    
                    console.log(image.index());
    
                    // Remove the image from the array by getting it's index.
                    // NOTE: The order of the filesArray will be the same as you see it displayed, therefore
                    //       you simply need to get the file's index to "know" which item from the array to delete.
                    console.log('Files:' ,filesArray);
                    removeFile(image.index());
                    console.log('Files:' ,filesArray);
    
                    // Fadeout the image and remove it from the UI.
                    image.fadeOut(function(){
                        $(this).remove();
                    });
                });
    
    
                /**
                 * This function processes the submission of the form.
                 *
                 * @param e
                 */
                function submitForm(e){
                    // Stop the form from actually submitting.
                    e.preventDefault();
    
                    // Create a new FormData based on our current form.
                    // Makes live easier as we can attach a list of File objects.
                    var formData = new FormData($('#myForm')[0]);
                    for(var i= 0, file; file = filesArray[i]; i++){
                        formData.append('files[]', file);
                    }
    
                    // Send the ajax request.
                    $.ajax({
                        url: 'upload.php',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(response) {
                            $('#response').html(jsonPrettify(response));
                        }
                    });
                }
                // Attach on submit to the form submission.
                $('#myForm').on('submit', submitForm);
            });
        </script>
    
    </head>
    
    <body>
    
        <div style="width: 650px; border: 1px #D8D8D8;">
    
            <form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
                <label>Name</label>
                <input type="text" name="firstName" value="FirstName"/>
                <input type="text" name="lastName" value="LastName"/>
    
                <!-- Don't set a name of this input so that we won't need to remove it before serialization. -->
                <input id="fileInput" type="file" value="Upload button" multiple/>
    
                <div style="width: 600px; border: 1px solid #D8D8D8;">
                    <ul style="list-style: none;" id="imagePreviews">
                    </ul>
    
                    <div style="clear: both;">&nbsp;</div>
                </div>
    
                <br>
    
                <input type="submit"/>
    
            </form>
    
            <br>
            Upload.php response<br>
            <pre id="response" style="width: 650px;"></pre>
        </div>
    
    </body>
    </html>
    
    // upload.php
    <?php
    
    header('Content-Type: application/json');
    echo json_encode(array('success' => true, '$_FILES' => $_FILES, '$_POST' => $_POST));
    
    ?>