Показать сообщение отдельно
  #1 (permalink)  
Старый 27.07.2012, 21:53
Аспирант
Отправить личное сообщение для ksevelyar Посмотреть профиль Найти все сообщения от ksevelyar
 
Регистрация: 21.03.2009
Сообщений: 53

Удаление элементов из files[i] (<input multiple="">)
Хочу, чтобы можно было выборочно удалять изображения после добавления их через <input multiple="">.

Но напрямую это сделать видимо нельзя: http://www.w3.org/TR/FileAPI/#dfn-filelist

"The HTMLInputElement interface [html] has a readonly attribute of type FileList, which is what is being accessed in the above example. Other interfaces with a readonly attribute of type FileList include the DataTransfer interface [html]".

Как можно это обойти и удалять files[i] по клику на .remove?

Извиняюсь за смесь js и jquery:

http://jsfiddle.net/mUHeU/1/

$(document).ready(function() {

var fileSelect = document.getElementById("fileSelect"),
    fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", function (e) {
  if (fileElem) {
    fileElem.click();
  }
  e.preventDefault(); // prevent navigation to "#"
}, false);

$('#fileElem').change(function()
{
  handleFiles(this.files);
});


function bytesToSize(bytes) {
  var kilobyte = 1024;
  var megabyte = kilobyte * 1024;
  var gigabyte = megabyte * 1024;
  var terabyte = gigabyte * 1024;

  if ((bytes >= 0) && (bytes < kilobyte)) {
    return bytes;

  } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
    return (bytes / kilobyte).toFixed(0) + 'K';

  } else if ((bytes >= megabyte) && (bytes < gigabyte)) {
    return (bytes / megabyte).toFixed(1) + 'M';

  } else if ((bytes >= gigabyte) && (bytes < terabyte)) {
    return (bytes / gigabyte).toFixed(2) + 'G';

  } else if (bytes >= terabyte) {
    return (bytes / terabyte).toFixed(2) + 'T';

  }
}


function handleFiles(files) {
  var d = document.getElementById("filelist");
  var list = document.createElement("ul");
  d.appendChild(list);
  for (var i=0; i < files.length; i++) {
    var li = document.createElement("li");
    list.appendChild(li);

    var a = document.createElement("a");
    a.setAttribute('href','#');
    a.setAttribute('alt','');
    li.appendChild(a);

    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(files[i]);;
    img.onload = function() {
      window.URL.revokeObjectURL(this.src);
    }
    a.appendChild(img);

    var name = $("<span class='name'>" + files[i].name + "</span>");
    $(a).append(name);

    var size = $("<span class='size'>" + bytesToSize(files[i].size) + "</span>");
    $(a).append(size);

    var remove = $("<a href='#remove' id=" + i + " class='remove'>remove</a>");
    $(li).append(remove);

  }
}

$('.remove').live("click", function(event) {
  event.preventDefault();
  alert("Handler for .click() called.");
});


});
Ответить с цитированием